How to create a user in MongoDB v3?

To create a user in MongoDB v3, use the createUser() method. This allows you to create a user by specifying the username, password, and roles that assign specific permissions to databases.

Syntax

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

Example

Let us create a user named "Robert" with readWrite permissions on the "sample" database ?

use admin
db.createUser(
    {
        user: "Robert",
        pwd: "robert",
        roles: [ { role: "readWrite", db: "sample" } ]
    }
);

This will produce the following output ?

Successfully added user: {
    "user" : "Robert",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "sample"
        }
    ]
}

Key Points

  • User creation must be done from the admin database
  • Roles define what permissions the user has on specific databases
  • Common roles include read, readWrite, dbAdmin, and userAdmin

Conclusion

The createUser() method in MongoDB v3 allows you to create users with specific roles and database permissions. Always switch to the admin database before creating users to ensure proper authentication setup.

Updated on: 2026-03-15T00:53:41+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements