All academies
Roadmap
LEVEL 11 · SECURITY

Securing MongoDB

12 min read

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.

mongosh
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.

mongosh
// 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) })

Check your understanding

Q1.

A reporting service only needs to read the 'analytics' database. Which role fits best?

Q2.

A login form passes req.body.user directly into a query. An attacker sends { "$ne": null }. What happens?

code
db.users.findOne({ username: req.body.user })
Q3.

It's fine to expose MongoDB directly to the internet if you have a strong password.