How to create MongoDB user on existing database with correct role?

To create a new user in MongoDB, use the createUser() method on an existing database. This allows you to assign specific roles and authentication mechanisms to control user permissions.

Syntax

db.createUser({
    user: "username",
    pwd: "password",
    roles: [
        { role: "roleName", db: "databaseName" }
    ],
    mechanisms: ["SCRAM-SHA-256"]
});

Example: Create User with readWrite Role

Create a user named "John" with readWrite permissions on the test database ?

db.createUser({
    user: "John",
    pwd: "123456",
    roles: [ { role: "readWrite", db: "test" } ],
    mechanisms: [ "SCRAM-SHA-256" ]
});

This will produce the following output ?

Successfully added user: {
    "user" : "John",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-256"
    ]
}

Verify User Creation

To display all users in the current database ?

db.getUsers();

This will produce the following output ?

[
    {
        "_id" : "test.John",
        "user" : "John",
        "db" : "test",
        "roles" : [
            {
                "role" : "readWrite",
                "db" : "test"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-256"
        ]
    }
]

Key Points

  • The createUser() method must be run on the target database where you want to create the user.
  • readWrite role allows the user to read and write data in the specified database.
  • SCRAM-SHA-256 is the recommended authentication mechanism for security.

Conclusion

Use createUser() to create database users with specific roles and permissions. Always specify the target database in the role definition and use secure authentication mechanisms like SCRAM-SHA-256.

Updated on: 2026-03-15T02:53:07+05:30

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements