0
0
MongodbHow-ToBeginner · 4 min read

How to Assign Role to User in MongoDB: Simple Guide

In MongoDB, you assign a role to a user by using the db.createUser() command when creating the user or db.updateUser() to modify roles of an existing user. Roles define the permissions the user has on the database.
📐

Syntax

To assign roles to a user in MongoDB, you use either db.createUser() to create a new user with roles or db.updateUser() to change roles of an existing user.

  • db.createUser({user: "username", pwd: "password", roles: [<role objects>]}): Creates a user with specified roles.
  • db.updateUser("username", {roles: [<role objects>]}): Updates roles for an existing user.
  • Each role object has role (role name) and db (database where role applies).
mongodb
db.createUser({
  user: "exampleUser",
  pwd: "examplePass",
  roles: [
    { role: "readWrite", db: "testDB" },
    { role: "read", db: "reportsDB" }
  ]
})
💻

Example

This example shows how to create a user named reportUser with the read role on the reports database, then update the user to add the readWrite role on the same database.

mongodb
use admin

db.createUser({
  user: "reportUser",
  pwd: "securePass123",
  roles: [ { role: "read", db: "reports" } ]
})

// Later, update user to add readWrite role

db.updateUser("reportUser", {
  roles: [
    { role: "read", db: "reports" },
    { role: "readWrite", db: "reports" }
  ]
})
Output
{ "ok" : 1 }
⚠️

Common Pitfalls

Common mistakes when assigning roles include:

  • Not specifying the correct database for the role, which causes the role to not apply as expected.
  • Trying to assign roles without proper privileges, leading to authorization errors.
  • Forgetting to switch to the admin database when creating or updating users, since user management commands usually run there.
mongodb
/* Wrong: Missing db field in role */
db.createUser({
  user: "user1",
  pwd: "pass1",
  roles: [ { role: "readWrite" } ]
})

/* Right: Include db field */
db.createUser({
  user: "user1",
  pwd: "pass1",
  roles: [ { role: "readWrite", db: "test" } ]
})
📊

Quick Reference

CommandPurposeExample
db.createUser()Create a new user with rolesdb.createUser({user: "alice", pwd: "pwd", roles: [{role: "read", db: "sales"}]})
db.updateUser()Update roles of existing userdb.updateUser("alice", {roles: [{role: "readWrite", db: "sales"}]})
role objectDefines role and database{role: "read", db: "testDB"}

Key Takeaways

Use db.createUser() to assign roles when creating a new user in MongoDB.
Use db.updateUser() to change roles of an existing user.
Always specify both role name and database in the roles array.
Run user management commands in the admin database for proper effect.
Ensure you have the necessary privileges to assign roles.