top of page

How to Create a User in MongoDB using db.createUser() Method


Create a User in MongoDB

To create a user in MongoDB, you can use the db.createUser() method. Here is the basic syntax:


test> use builddevops
switched to db builddevops
builddevops> db.createUser({user: "siddhesh",pwd: "P@ssw0rd",roles: ["read"]})
{ ok: 1 }
builddevops>

Let's break down the parameters used in db.createUser():


user: The username for the new user.

pwd: The password for the new user.

roles: An array of roles granted to the user. MongoDB has several built-in roles like read, readWrite, dbAdmin, etc.

This command creates a user named 'siddhesh' with the password 'P@ssw0rd' and grants the user the read role on the 'builddevops'. Adjust the roles based on the specific needs of your application.


Remember to switch to the appropriate database using the use command before creating the user.

Verify:


[root@siddhesh ~]# mongosh -u siddhesh -p --authenticationDatabase builddevops
Enter password: ********
Current Mongosh Log ID:	656dba78ec085f4b8ed81c13
Connecting to:		mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=builddevops&appName=mongosh+2.1.0
builddevops> 

where, mongosh: This is the MongoDB Shell, which is a JavaScript shell interface for MongoDB.


-u siddhesh: This option specifies the username for authentication. In this case, the username is "siddhesh".


-p: This option prompts you to enter the password interactively. When you run the command, it will ask you to enter the password for the specified user.


--authenticationDatabase builddevops: This option specifies the authentication database. In MongoDB, users are typically associated with a specific database where their credentials are stored. In this case, the authentication database is "builddevops".

bottom of page