How do I change a MongoDB user's password?


You need to use changeUserPassword() to change a user’s password. Let us first create a user with some roles. Following is the query to create a user in MongoDB −

> use admin
switched to db admin
> db.createUser(
...    {
...       user: "Chris",
...       pwd: "chris",
...       roles: [ { role: "readWrite", db: "test" } ]
...    }
... );
Successfully added user: {
   "user" : "Chris",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ]
}

Let us display the user from test database −

> db.getUser("Chris");

This will produce the following output −

{
   "_id" : "admin.Chris",
   "user" : "Chris",
   "db" : "admin",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}

Following is the query to change a MongoDB user's password.

> db.changeUserPassword("Chris", "123456");

The password has been changed.

Updated on: 30-Jul-2019

925 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements