MongoDB Security Hardening: A Production Checklist
A production checklist for locking down MongoDB: authentication, network restrictions, scoped users, query safety, bulk-write guards, backups and monitoring.
MongoDB security hardening is rarely exciting work, and that is why it gets postponed. The database starts on a developer's laptop with no password, gets deployed with the same defaults, and stays that way until the data inside it becomes valuable.
This is the checklist I work through before calling a MongoDB deployment production-ready. It covers the obvious layers (authentication and network access) and the less obvious one that causes a lot of real damage: application code that sends a destructive query with the wrong filter.
TL;DR
Enable authentication, keep MongoDB off the public internet, use TLS, give every app its own least-privilege user, and store credentials as secrets. Then protect the data from your own code by validating filters on bulk writes, and prove your backups work by restoring them on a schedule.
key takeaways
- Authentication must be on and the database must never be reachable from the public internet, regardless of how strong the password is.
- Give each application its own database user with only the roles it needs, and keep admin credentials out of app servers.
- Many real data-loss risks come from your own code, so guard bulk updates and deletes against empty or malformed filters.
- Backups only count if you have restored one recently, so schedule a restore drill alongside the backup job.
Layer 1: authentication and network access
These two controls stop most opportunistic attacks. Automated scanners constantly look for open database ports, so an unauthenticated MongoDB on a public IP is a matter of when, not if.
Authentication. On self-hosted MongoDB, set security.authorization: enabled in mongod.conf, create an admin user, then restart. On Atlas it is on by default. Use SCRAM-SHA-256 or x.509 certificates.
Network. The database should only accept connections from your app servers.
- Set
net.bindIpto localhost and the private interface, never0.0.0.0unless a firewall sits in front. - Use cloud firewall rules or security groups that allow port 27017 only from app server IPs or a private subnet.
- On Atlas, keep the IP access list tight and avoid
0.0.0.0/0, even "temporarily". - Prefer private networking (VPC peering or private endpoints) between app and database.
Encryption in transit. Turn on TLS for client connections and replica set traffic. Atlas enforces it. Self-hosted clusters need certificates and net.tls.mode: requireTLS.
The official MongoDB security checklist is worth reading alongside this one.
Layer 2: users, roles and secrets
Once only your servers can connect, limit what each connection can do.
| User | Roles | Used by |
|---|---|---|
app_api |
readWrite on the app database only |
Node API servers |
app_worker |
readWrite on the app database only |
Cron jobs, queue workers |
reporting_ro |
read on the app database |
BI tools, analysts |
backup_svc |
backup |
Backup job |
dba_admin |
userAdminAnyDatabase, clusterAdmin |
Humans, rarely, from a bastion |
Separate users for API and workers seem fussy until you need to rotate one credential without restarting everything. A read-only user for reporting means a spreadsheet integration cannot accidentally write.
Secrets handling:
- Keep connection strings out of the repo, including
.env.examplefiles with real hosts. - Store them in your cloud's secret manager or a locked-down env file readable only by the service user.
- Rotate passwords when someone with access leaves, and on a regular schedule.
- Never log full connection strings. Sentry breadcrumbs and error messages are common leak paths.
Layer 3: protect the data from your own code
This is the layer most checklists skip. A perfectly locked-down database can still lose a collection to one bad updateMany.
Guard bulk operations
Consider Lead.updateMany({ assignedTo: req.body.userId }, { $set: { status: 'lost' } }). If userId is undefined, some drivers and ODM settings can turn that into a filter that matches far more documents than intended. Defensive patterns:
- Wrap
updateMany,deleteManyandbulkWritein a helper that rejects empty filters ({}) and filters where every value isundefinedornull. - Always include the tenant key (for example
businessId) in multi-tenant filters, and assert it is present in the helper. - Run
countDocuments(filter)first for destructive operations and refuse if the count exceeds a sane threshold without an explicitforceflag. - Log the filter, matched count and modified count for every bulk operation.
Validate input before it reaches a query
- Enable Mongoose
strictQueryso unknown fields in filters are dropped. - Reject objects where you expect strings, which blocks operator injection like
{ "$ne": null }in a login form. - Validate IDs with
isValidObjectIdbefore querying.
Indexes are a security control too
An unindexed query on a large collection can pin CPU and make the whole app unavailable. Add indexes for every hot filter and sort, and use explain() to confirm they are used. Slow queries are a denial-of-service risk you created yourself.
Layer 4: backups, monitoring and patching
- Automated backups: Atlas continuous backup, or scheduled
mongodump/ filesystem snapshots for self-hosted clusters, stored in a separate account or bucket. - Restore drills: restore last night's backup into a staging cluster monthly and run a smoke test against it.
- Audit and alerts: alert on failed authentication spikes, new users or roles, and unusual connection sources.
- Patching: track MongoDB and driver releases and upgrade on a planned cadence rather than once something breaks.
- Disable what you do not use: server-side JavaScript, HTTP interfaces on old versions, and unused default databases.
How I built this in practice
On Antoc, the real-estate CRM used by 100+ firms in India, the MongoDB database had to be scaled and hardened as the number of managed leads grew past 300K. The work covered all of the layers above rather than any single fix.
In practice that meant three things. First, indexes on the queries that power lead lists, pipelines and reports, so heavy filters stayed fast as data grew. Second, safe bulk operations with filter validation, because lead imports from Meta lead ads, Google Sheets and portals plus auto-assignment rules generate a lot of bulk writes, and a missing filter value must never touch the wrong businesses. Third, authentication and network restrictions so the database is only reachable from the application servers.
The multi-tenant angle matters. In both Antoc and Client Mitra, every query is scoped by business, and in Client Mitra tenant isolation lives in middleware so a route cannot forget it. Treat the tenant key as part of your security model, not just your data model.
Common mistakes
- Opening the database to
0.0.0.0/0during a deploy and never closing it. - Running the app with an admin user because "it was easier during setup".
- Passing raw request bodies into filters, which allows operator injection.
- Allowing
deleteManyorupdateManywith filters built from possibly undefined values. - Taking backups for months without ever restoring one.
- Committing connection strings to the repo or printing them in error logs.
keep reading
- Cloud and DevOps services →
- How Antoc scaled MongoDB for 300K+ leads →
- Hire a full stack developer in Dubai →
- GitHub Actions self-hosted runner setup and gotchas →
- Azure data residency for Australian compliance apps →
- Production Node.js on AWS EC2 checklist →
- Building a self-hosted LAN file transfer app →
FAQ
What is the first step in MongoDB security hardening?+
Turn on authentication and close the database to the public internet. Bind MongoDB to private interfaces, restrict access with firewall rules or an IP access list, and only then worry about finer controls.
Is MongoDB Atlas more secure than self-hosting?+
Atlas gives you encryption, TLS, backups and access lists by default, which removes many easy mistakes. Self-hosting can be just as secure, but you own every setting, patch and backup.
How do I stop a bad query from wiping a collection?+
Wrap bulk updates and deletes in a helper that rejects empty or missing filters, logs the filter and matched count, and requires an explicit flag for operations above a threshold. Mongoose's strictQuery setting also helps by dropping unknown filter fields.
Should application users have the readWrite role on all databases?+
No. Scope each app user to the one database it needs, and create separate read-only users for analytics or reporting tools so a leaked credential has limited reach.
Devang Gandhi
AI & full stack developer at Passdn, building CRMs, SaaS, AI agents and Flutter apps for clients in the US, UK, Australia, UAE and India. More about me