How can I use a script to create users in MongoDB?

You can create users in MongoDB using the createUser() method. This method allows you to define username, password, and specific roles for database access control.

Syntax

db.createUser(
    {
        user: "yourUserName",
        pwd: "yourPassword",
        roles: [ { role: "roleType", db: "databaseName" } ]
    }
);

Example

Let us create a user named "David" with read access to the "test" database ?

db.createUser(
    {
        user: "David",
        pwd: "David123456",
        roles: [ { role: "read", db: "test" } ]
    }
);

This will produce the following output ?

Successfully added user: {
    "user" : "David",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}

Common Role Types

  • read ? Read-only access to the database
  • readWrite ? Read and write access to the database
  • dbAdmin ? Database administration privileges
  • userAdmin ? User management privileges

Conclusion

The createUser() method provides a straightforward way to create users with specific roles and database permissions. Always assign appropriate roles based on the user's required access level for security purposes.

Updated on: 2026-03-15T00:51:42+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements