Create User in MongoDB – Easy Step-by-Step Guide:

Create User in MongoDB

Prerequisites

To create a user in MongoDB, ensure you have:

  • MongoDB installed and running
  • Access to the MongoDB shell (mongosh or mongo)
  • Administrative privileges to create new users

MongoDB User Roles :

MongoDB provides role-based access control (RBAC) to manage database security. Some common roles include:

  • read: It allows read-only access to a database.
  • readWrite: It allows both read and write access.
  • dbAdmin: Provides administrative privileges within a database.
  • userAdmin: It allows user creation and role assignment.
  • root: Grants full access to all databases.

Create User in MongoDB :

Step 1: Connect to MongoShell :

Open your terminal and connect to MongoDB:

mongo

Or, if the authentication is enabled, issue below command :

mongosh -u admin -p --authenticationDatabase admin

Step 2: Switch to the required Database :

Step 3 :Create User In Mongodb :

Syntax :
db.createUser({
user: "username",
pwd: "password",
roles: [{ role: "rolename", db: "sample_new" }]
});

Example :
db.createUser({
user: "John",
pwd: "pwd123",
roles: [{ role: "readWrite", db: "sample_new" }]
});

Output :

Create User in MongoDB – Easy Step-by-Step Guide:

Step 4: Verify the User :

db.getUsers()

Output :

Create User in MongoDB – Easy Step-by-Step Guide:

Hope this helps to learn how to add user in MongoDB with detailed steps!! Also, you can get more information from the MongoDB Official Doc as well.

Other MongoDB Related Articles :

Leave a Reply