MongoDB Security and Backups
MongoDB security and backups are essential before going to production. Thousands of databases have been leaked because they were exposed to the internet without a password, so treat these steps as mandatory.
Creating Users with Roles
Grant each application only the roles it needs on its own database (principle of least privilege).
use admin
db.createUser({
user: "shopApp",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "shop" } ]
})Enter password
********{ ok: 1 }Security Checklist
- Enable authentication (security.authorization: enabled in mongod.conf); Atlas does this for you
- Bind to private interfaces only and use firewall or IP allowlists
- Use TLS for all connections
- Store connection strings in environment variables or a secrets manager
- Validate and sanitise user input to avoid query injection, e.g. reject objects where strings are expected
Query Injection Example
If you pass request data straight into a filter, an attacker can send { "$ne": null } as a password. Force values to strings.
// Vulnerable: req.body.password could be { $ne: null }
await users.findOne({ email: req.body.email, password: req.body.password })
// Safer
await users.findOne({ email: String(req.body.email) })The safer version only ever compares against a plain string.
Backups with mongodump and mongorestore
mongodump writes BSON files for a database; mongorestore loads them back. Atlas also provides automated cloud backups.
mongodump --uri="mongodb://127.0.0.1:27017" --db=shop --out=./backup
mongorestore --uri="mongodb://127.0.0.1:27017" --nsInclude="shop.*" ./backupdone dumping shop.products (7 documents) done dumping shop.customers (3 documents) ... 10 document(s) restored successfully. 0 document(s) failed to restore.
Frequently asked questions
Is MongoDB secure by default?
Since 3.6, MongoDB binds only to localhost by default, but authentication is still off on a self-installed server until you enable it. Atlas enforces authentication and TLS.
How do I back up a MongoDB database?
Use mongodump and mongorestore for small to medium databases, filesystem snapshots for large ones, or Atlas Cloud Backup for managed clusters.
Should I store passwords in MongoDB?
Only as strong hashes created with bcrypt or Argon2, never in plain text.