DBAtlas · Database operations atlas

Define a custom role, create a user, grant/revoke roles and change the password

MongoDBSecurity

Command

use admin
db.createRole({
  role: "opsRead",
  privileges: [
    { resource: { db: "shop", collection: "" }, actions: ["find", "listCollections", "listIndexes", "collStats", "dbStats"] },
    { resource: { cluster: true }, actions: ["serverStatus", "inprog"] }
  ],
  roles: []
})
db.createUser({ user: "shop_app", pwd: passwordPrompt(), roles: [{ role: "readWrite", db: "shop" }, { role: "opsRead", db: "admin" }] })
db.grantRolesToUser("shop_app", [{ role: "clusterMonitor", db: "admin" }])
db.revokeRolesFromUser("shop_app", [{ role: "clusterMonitor", db: "admin" }])
db.changeUserPassword("shop_app", passwordPrompt())
db.getUser("shop_app", { showPrivileges: true })
db.runCommand({ usersInfo: { forAllDBs: true } })

What it does

Defines a custom role with specific database and cluster actions, creates a user with that role and built-in roles, grants and revokes roles, changes the password and lists users across all databases.

When to use it

When creating application and monitoring accounts under least privilege, during access reviews or password rotation.

Caution

The database where the user is defined (admin here) is used as authSource; it must match the application's connection string. Do not grant broad roles such as root/dbOwner to application accounts. Role changes apply to existing sessions immediately; a password change does not drop open connections and applies to new ones.

Open in DBAtlas →