
MongoDB is a popular NoSQL database that offers flexible and scalable data management. To enhance security, it is essential to create users with appropriate roles and privileges in the database. This guide walks you through the steps to create a user in MongoDB and user management and set up authentication properly with detailed steps. Let’s go through this:
Table of Contents
Prerequisites
To create a user in MongoDB, ensure you have:
- MongoDB installed and running
- Access to the MongoDB shell (
mongosh
ormongo
) - 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 :

Step 4: Verify the User :
db.getUsers()
Output :

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 :
- Understanding the Difference Between RDBMS and MongoDB: 4 top features
- Install MongoDB in Redhat Linux with 5 Easy Steps