MongoDB create and change user password

In this MongoDB tutorial, We are going to learn “How MongoDB create and change user password”. We will also cover this topic using different operations. These are the following topics that we are going to cover in this tutorial:

  • MongoDB create the user password
  • MongoDB create user password example
  • MongoDB change the user password
  • MongoDB change user password example in Windows
  • MongoDB change the user password in Ubuntu
  • MongoDB atlas change user password
  • MongoDB compass set user password
  • MongoDB compass change user password
  • MongoDB change admin user password
  • MongoDB change db user password
  • MongoDB change the current user password
  • MongoDB create root user password

MongoDB create the user password

In MongoDB, we can create a new user for the database by using the db.createUser() method, and this method return error only if the user already exists in the database.

Syntax:

The db.createUser() method has the following syntax:

db.createUser(user, writeConcern)
FieldsTypeDescription
userdocumentDocument with authentication and access
information about the user to create.
writeConcerndocumentsOptional, It is used for the creation operation.

Here, the user documents define the user and have the following form:

{
  user: "<name>",
  pwd: passwordPrompt(),      // Or  "<cleartext password>"
  customData: { <any information> },
  roles: [
    { role: "<role>", db: "<database>" } | "<role>",
    ...
  ],
  authenticationRestrictions: [
     {
       clientSource: ["<IP>" | "<CIDR range>", ...],
       serverAddress: ["<IP>" | "<CIDR range>", ...]
     },
     ...
  ],
  mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ],
  passwordDigestor: "<server|client>"
}

The user documents have the following fields:

FieldTypeDescription
userstringThe name of the new user
pwdstringThe user password. The pwd field
is not required if you run db.createUser()
on the external database. The value can be:
-> the user password in cleartext string or,
-> the passwordPrompt() to prompt the user password.
customDatadocuments Optional, this field can be used to store any data and can be associate with any particular user.
rolesarrayCan specify an empty array[] to create users without roles.
authenticationRestricationarrayOptional, The authentication restrictions the server enforces on the created user.
mechanismsarrayOptional. Used to specify the specific SCRAM mechanism or mechanisms for creating SCRAM user credentials.
passwordDigesterstringOptional. It indicates whether the server or the client digests the password.

Thus, this way you can create the user password for a database.

Read: MongoDB Update Documents

MongoDB create user password example

In this topic, we will learn to create user password with the help of an example.

To set the user password follow the below steps:

  • Start the MongoDB server by using the mongod command
> mongod --dbpath="specify the path of MongoDB"
Start the MongoDB Server
Start the MongoDB Server

Note that, In the shell, I don’t specify the path because the path of MongoDB is already set in the environment variable in my system.

If you don’t set the path of MongoDB in the environment variable then you have to write the exact path where MongoDB is stored to start the server.

  • Again, open a new command prompt and start the MongoDB shell by using the mongo command
> mongo
Start the MongoDB shell
Start the MongoDB shell
  • Now, we will create the user passwod by using the createUser() method.
> show dbs
admin    0.000GB
config   0.000GB
local    0.000GB

> use admin
switched to db admin

> db.createUser({"user": "demo", "pwd": "demo123",
    "roles": [{ "role": "userAdminAnyDatabase", "db": "admin"}]
 })

Here, we use the admin database to set the user password by using the createUser() method. Here, we set the user name as demo and password as demo123. And also set the roles to set the role and database.

You can use any name for the user and password and set the user password.

See the execution of the code in MongoDB Shell:

MongoDB create the user password
MongoDB create the user password

Here, see in the output after executing the code we successfully added the user and roles.

  • Now, we created the user but our database connection is not authenticated because right now we are performing these operations without authenticate the database.
  • So to perform the operation in authentication mode then first stop the MongoDB server and Shell.
  • Use command “Ctrl + C” to stop the MongoDB server.
  • To start the server in access control mode use the below command
> mongod --auth --dbpath="specify the path of MongoDB"

This command will start the MongoDB server in access control mode.

Start the MongoDB Server in --auth mode
Start the MongoDB Server in –auth mode
  • Now again start the MongoDB Shell

Now we can start the MongoDB shell two ways:

  • Authenticate after connecting: In this method first, we connect to the MongoDB server and then authenticate by following commands:
> mongo

> use admin
> db.auth("demo","demo123")  #or db.auth({ "user":"demo", "pwd": "demo123" })

Here, the db. auth() allow a user to authenticate to the database within the shell. And, the username and password are the same “demo” and “demo123” respectively those we created earlier.

Note that, you can use any command for the authentication both commands are valid.

See the execution of the code in MongoDB shell:

MongoDB create user password example
MongoDB create the user password

The auth() method returns as 1 it means we are successfully authenticated. If it returns 0 means we didn’t write the correct user password and are unable to authenticate.

Now after login we can use the MongoDB database and perform different operations.

  • Authenticate before connecting: In this method, we define the username and password with the mongo command so we don’t need to authenticate again after start the server.

The following command is used for this:

> mongo --u "username" --p "password" --authenticationDatabase "admin"

In this command, authenticate when connecting to the shell write –username, –password, –authenticationDatabase and –authenticationMechanism to specify authentication credentials when connecting mongo

See the execution of the code in MongoDB shell:

MongoDB create the user password example
MongoDB create the user password

Here, both the ways are to correct to start the MongoDB database in access control mode. It depends upon you which way you start the MongoDB shell.

Read: How to drop a database in MongoDB

MongoDB change user password

In MongoDB, Sometimes we forget the user password, or either we want to change the user password so in that situation we have to change or update the user’s password.

The changeUserPassword() method is used to change the user password.

Syntax:

db.changeUserPassword(username, password)
ParameterTypeDescription
usernamestringThe user name whose password we want to change.
passwordstringThe user password value can be either:
-> The user password in cleartext string, or
-> Use passwordPrompt() to prompt for the user password.
(starting in version 4.2 of Mongo shell, we can use passwordPrompt() method)
writeConcerndocumentsOptional, The level of write concern for the creation operation.

Note:

Even if you use passwordPrompt, db.changeUserPassword() sends all given data to the MongoDB instance in cleartext by default. Use TLS transport encryption to protect the communication between clients and the server, including the password sent by db.changeUserPassword().

MongoDB does not store the password in cleartext. If TLS transport encryption is not enabled then the password is vulnerable in transit between the client and the server.

Read: Export MongoDB to CSV

MongoDB change the user password example in Windows

In windows operating systems, the MongoDB shell manages the MongoDB database very conveniently. We can perform all the operations of MongoDB by using the MongoDB shell.

We can also change the user password from the MongoDB shell by following the below steps:

  • Start the MongoDB server in access control mode
> mongod --auth
  • Again open the command prompt and authenticate when connecting to the shell by using below command.
> mongo --u "username" --p "password" --authenticationDatabase "admin"

Here, write the username, password, and database name for authentication.

  • Now Check the list of user of the database by using command
> use admin

> db.getUsers()
MongoDB change the user password
MongoDB change the user password

Here, we use the admin database and the getUsers() method will display a list of users of the database that also helps you to which particular user password you want to change. See, there are two users “demo” and “test” in the admin database.

  • Now, we will change the user password by using the changeUserPassword() method.

There are two ways to change the password of a user. And, we will learn both ways to change the password:

  • cleartext password
  • passwordPrompt() method

ClearText password: Here, we write the password in clearText (string) form in the changeUserPassword() method. Use the below command to change the password.

> db.changeUserPassword( "user_name", "new_password")
MongoDB change user password in Windows
MongoDB change the user password

Here, we changed the password of the test user and write the new password “[email protected]” in clearText (String).

After executing the command, if you didn’t find any error then you have successfully changed the password of the user.

passwordPrompt(): Use the below command to change the password of the user of a database:

> db.changeUserPassword( "test", passwordPrompt() )
Enter password:
>

Here, we use the changeUserPassword() method and write the parameter the username which password you want to change. And use passwordPrompt() instead of specifying the password (clearText).

The passwordPrompt() method prompts you to enter the new password so write the password and press enter. And, we have successfully changed the password.

Read: MongoDB join two collections

MongoDB change the user password in Ubuntu

In ubuntu operating systems, the MongoDB shell manages the MongoDB database very conveniently. We can perform all the operations of MongoDB by using the MongoDB shell.

You can easily change the user password from the MongoDB shell in Ubuntu operating system by following the below steps:

  • In ubuntu to start the MongoDB server by using the below command
service mongodb start
  • After that, start the MongoDB shell to change the user password
mongo -u "username" -p "user_password"

Here, write the username and password for the authentication.

MongoDB change the user password in Ubuntu
MongoDB change the user password in Ubuntu
  • Now Check the list of users of the database by using the below command
> show dbs

> db.getUsers()
MongoDB change the user password example
MongoDB change the user password

Here, we use the getUsers() method to display a list of users of the database and this helps you to which particular user password you want to change. There is only one user “test“.

  • Now, we will change the user password by using the changeUserPassword() method.

There are two ways to change the password of a user. And, we will learn both ways to change the password:

  • Cleartext password
  • passwordprompt() method

Cleartext password: Here, we write the password in clearText (string) form in the changeUserPassword() method. Use the below command to change the password:

> db.changeUserPassword( "user_name", "new_password")
MongoDB change the user password example
MongoDB change the user password

Here, we changed the password of the test user and write the new password “@123test” in cleartext. And after writing the command press enter and if you didn’t find any error then you have successfully changed the password of the user.

passwordPrompt(): Use the below command to change the password

> db.changeUserPassword( "test", passwordPrompt() )
Enter password:
>

We use the changeUserPassword() method and write the parameter. The username which password you want to change. And, use passwordPrompt() instead of specifying the password (clearText).

The passwordPrompt() method prompts you to enter the new password so write the password and press enter. And this will change the user password. we have successfully changed the password.

Note: If you want to use the passwordPrompt() then your MongoDB version must be greater than equal to 4.2 then only you can use this method.

Also, Read: Import CSV into MongoDB

MongoDB atlas change user password

The MongoDB Atlas is a fully-managed cloud database that handles all the complexity of deploying, managing, and healing your deployments on the cloud service provider of your choice (AWS, Azure, and GCP). 

You can easily change the user password of the cluster by using following the below steps:

  • Login to the MongoDB atlas
  • Select the project and cluster in which you want to change the user password.
MongoDB atlas change user password
MongoDB atlas change user password
  • Click on Connect button
MongoDB atlas change the user password
MongoDB atlas change user password
  • After that click on Setup connection security and also click on MongoDB users tab
Atlas change user password
MongoDB Atlas change the user password
  • The MongoDB Users tab open a new tab of Database Access.
  • Here you see all the database user name select the user to change the password.
  • To change the password of test user click on EDIT button.
Change user password in MongoDB Atlas
MongoDB Atlas change the user password
  • Click on Edit Password button
Atlas change the user password
MongoDB atlas change user password
  • Now, Enter the New Password and click on Update User button
Change user password in MongoDB Atlas
MongoDB atlas change user password
  • We succesfully changed the user password in MongoDB atlas.
  • Now to check that password has changed or not start the MongoDB shell
  • Below command is used to start the MongoDB Atlas server
mongo "mongodb+srv://testcluster.iofia.mongodb.net/myFirstDatabase" --username test

Here, we write the mongo command to start the server and the connection string of the cluster which user password we changed.

Start the MongoDB server using MongoDB shell
Start the MongoDB server using MongoDB shell

Now It will ask to enter the password so enter the new password. Thus our MongoDB shell starts successfully.

Read: How to Create a project and cluster in MongoDB Atlas?

MongoDB compass set the user password

In MongoDB compass, if we want to authenticate the user to a particular database then in that situation we have to provide the user and password.

Note that, we select the username and password if the deployment uses either MongoDB-CR or SCRAM-SHA-1 as its authentication mechanism.

Prerequisites:

To be able to create users, you need to:

  • enable access control
  • create a user administrator

Now, you need to follow the below steps to create a user:

  • Open MongoDB Compass
  • Click on Fill in connection fields individually
MongoDB compass change user password
MongoDB compass set user password
  • Here, some fields are autofields
  • Click on Authentication drop-down list and select Username/Password
MongoDB compass change the user password
MongoDB compass change the user password
  • Write the Username, Password, and Authentication Database.
MongoDB compass set user password
MongoDB compass set user password

Or if you are using the MongoDB shell then use the below command

mongo --port 27017 -u "test" --authenticationDatabase "admin" -p
  • Click on Connect button and this will connect you to Authenticate database.
  • Use the db.createUser() method to create additional users

The following operation adds a user Tester to the test database who has the readWrite role in the test database as well as the read role in the reporting database

use test
db.createUser(
  {
    user: "Tester",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

Here, the passwordPrompt() method prompts you to enter the password. We can also specify the password directly as a string. The passwordPrompt() method is used to avoid the password being visible on your screen and potentially leaking the password to your shell history.

See the execution of the code in the MongoDB shell (MONGOSH):

MongoDB compass set the user password
MongoDB compass set the user password

Note that, As we are working on MongoDB Compass so we are executing all the commands in the compass shell (MONGOSH). You can also use the command prompt MongoDB shell for the execution of these commands.

The database (test) where we create the user is the user’s authentication database.

  • After creating the additional users disconnect (exit) from the MongoDB Compass.
  • Connect to the instance and authenticate as Tester

Note that, It is not possible to switch between the users in the same MongoDB shell session. So to switch between users disconnect (exit) and relaunch the MongoDB Compass.

  • After existing MongoDB shell as test, reconnect as Tester by using the Compass
Compass set the user password
MongoDB Compass set the user password

Or if you are using the MongoDB shell then use the below command

mongo --port 27017 -u "Tester" --authenticationDatabase "test" -p
  • Enter the password for the user when prompted.
  • Now, Insert a documents as Tester

Once authenticated as Tester, insert a document into a collection in the test database. For example, you can perform the following insert operation in the test database:

db.demo.insert( { x: 1, y: 1 } )

As the user Tester, you have powers to perform read and write operations in the database (as well as perform read operations in the reporting database).

This way we can easily create (set) the user password in the production environment.

Read: MongoDB group by multiple fields

MongoDB compass change user password

In MongoDB, we create the user in the production environment for the database. And sometimes we have to update or change the password. So to change the password use the below command:

db.changeUserPassword(username, password)

Now, understand how to change the user password of the user’s authentication database in MongoDB Compass. Let’s change the previously created user password so follow the below steps:

  • Open MongoDB Compass
  • Click on Fill in connection fields individually
MongoDB compass change user password
MongoDB compass change user password
  • Here, some fields are autofields
  • Click on Authentication drop-down list and select Username/Password
MongoDB compass change the user password
MongoDB compass change the user password
  • Write the Username, Password, and Authentication Database.
compass change user password
MongoDB compass change user password

Here, we write previously created username Tester“, password, and Authentication Database test“.

  • Click on Connect button and this will connect you to Authenticate database.
  • Now, we will change the password of the user
  • Go to MongoDB Compass shell MONGOSH
  • Check the list of users by using below command
db.getUsers()
Change user password in MongoDB Compass
MongoDB Compass Change user password
  • Here, we will change the password of Tester user by using the below command.
db.changeUserPassword("Tester", passwordPrompt() )
  • Here, the passwordPrompt() method prompts you to enter the new password. You can also define your password directly as a string.

Note that, the passwordPrompt() method is used to avoid the password being visible on your screen and probably leaking the password to your shell history.

compass change the user password
MongoDB Compass change user password
  • we successfully changed the password of user.

This way we can easily change the password of the user’s authenticated database in the production environment.

You may also like some of our tutorials on MongoDB.

In this tutorial, you have learned How MongoDB create and change user password”. We covered this topic using different operations. These are the following topics that we covered in this tutorial:

  • MongoDB create the user password
  • MongoDB create user password example
  • MongoDB change the user password
  • MongoDB change user password example in Windows
  • MongoDB change the user password in Ubuntu
  • MongoDB atlas change user password
  • MongoDB compass set user password
  • MongoDB compass change user password
  • MongoDB change admin user password
  • MongoDB change db user password
  • MongoDB change the current user password
  • MongoDB create root user password

Leave a Comment