MongoDB security rests on four pillars: authentication (who are you), authorization (what can you do), encryption (in transit and at rest), and network hardening (who can even connect).
Users and roles
Access control is role-based. Built-in roles include read, readWrite, dbAdmin, and cluster-level roles. Follow least privilege: an app that only reads analytics data gets read on that one database, nothing more.
use admin
db.createUser({
user: "appUser",
pwd: passwordPrompt(),
roles: [{ role: "readWrite", db: "shop" }]
})Network & injection
Never expose MongoDB to the public internet: bind to private interfaces, use TLS, and firewall/IP-allowlist connections (Atlas enforces this). In application code, never build queries by string concatenation from user input — pass user values only as values, and reject keys beginning with $ from untrusted input to prevent operator injection.
// vulnerable (user controls an object)
db.users.find({ name: req.query.name })
// if name = { "$ne": null } → returns ALL users!
// safe
db.users.find({ name: String(req.query.name) })