Create a new user and set role in MongoDB

To create a new user and set their role in MongoDB, use the createUser() method. The userAdminAnyDatabase role provides comprehensive administrative privileges across all databases.

Syntax

use admin
db.createUser(
    {
        user: "yourUserName",
        pwd: "yourPassword",
        roles: [ { role: "yourRoleName", db: "yourDatabaseName" } ]
    }
)

Example

Create a user with the "userAdminAnyDatabase" role ?

use admin
db.createUser(
    {
        user: "David Miller",
        pwd: "123456",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
    }
)

This will produce the following output ?

Successfully added user: {
    "user" : "David Miller",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

Key Points

  • Always switch to the admin database before creating administrative users
  • The userAdminAnyDatabase role allows managing users across all databases
  • Multiple roles can be assigned by adding them to the roles array

Conclusion

Use db.createUser() in the admin database to create users with specific roles. The userAdminAnyDatabase role provides broad administrative privileges for user management across all databases.

Updated on: 2026-03-15T03:47:43+05:30

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements