How do you create users and roles in MongoDB?

IntermediateHands-onMongoDB
Answer

Short answer

Enable authentication, then create users with db.createUser() in the database where they should authenticate, assigning built-in roles like read, readWrite, dbAdmin or custom roles. Apps should get readWrite on their own database only.

Examples

use admin
db.createUser({ user: "admin", pwd: passwordPrompt(), roles: ["root"] })

use shop
db.createUser({
  user: "shop_app",
  pwd: passwordPrompt(),
  roles: [{ role: "readWrite", db: "shop" }]
})
db.createUser({ user: "reporting", pwd: passwordPrompt(), roles: [{ role: "read", db: "shop" }] })

db.getUsers()
db.grantRolesToUser("reporting", [{ role: "read", db: "analytics" }])
db.dropUser("old_app")

Enable auth on a self-managed server

# /etc/mongod.conf
security:
  authorization: enabled
net:
  bindIp: 127.0.0.1,10.0.21.10      # never 0.0.0.0 without a firewall

Authentication database

A user created in shop must connect with authSource=shop (the default when the URI path is /shop); users created in admin need authSource=admin.

What to say in the interview

"Turn on authorization, create an admin in admin, then per-app users in their database with readWrite only, plus read-only users for reporting. The authSource in the connection string must match where the user was created."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB