Bot database basics: SQLite vs MongoDB for beginners
Variables in your code disappear when the bot restarts. If you want to remember settings, levels, warnings or economy balances, you need to store them in a file or a database.
SQLite
SQLite is a database stored in a single file. There is no separate server to run.
- Python includes the sqlite3 module in the standard library.
- Node.js has packages such as better-sqlite3, and recent versions of Node also include a built-in SQLite module (check your version).
- Great for small and medium bots with one process.
- The database file lives in your bot folder, so you can see it in the Files tab and back it up by downloading it.
MongoDB
MongoDB stores flexible JSON-like documents and normally runs as a separate server. Many people use a hosted service such as MongoDB Atlas, which has a free tier at the time of writing (check the current terms). Your bot connects using a connection string.
- Handy when your data does not fit neat tables.
- Lets several programs share the same data.
- Needs network access from your bot to the database.
Which one?
- Starting out, one bot, simple data: SQLite.
- Data shared between a bot and a website, or you already know MongoDB: MongoDB.
Safe habits
- Never build queries by joining user text into strings. Use parameters or your driver's query features to avoid injection.
- Keep database passwords and connection strings in your .env file.
- Back up regularly. For SQLite, stop the bot and copy the file, or use the backup tools your library provides.
- Use async-friendly libraries in Discord bots, since a slow query can freeze the bot.
- Create tables or collections at startup if they do not exist.
A note on storage
Your files live on your server's storage, so avoid unlimited logs or huge databases. Check your storage use now and then from the panel.
If you are stuck choosing, start with SQLite. It is easy to learn, and moving to another database later is possible if your bot outgrows it.