How to rename a username in MongoDB?


To rename a user, you need to use update() and $set to set the new username. Following is the syntax −

db.system.users.update({"user":"yourOldUserName"}, {$set:{"user":"yourNewUserName"}});

Firstly, display all the users from the MongoDB database −

> use admin;
switched to db admin

> db.getUsers();

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"
      ]
   },
   {
      "_id" : "admin.John",
      "user" : "John",
      "db" : "admin",
      "roles" : [
         {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   },
   {
      "_id" : "admin.Robert",
      "user" : "Robert",
      "db" : "admin",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "sample"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   }
]

Now rename user name from ‘John’ to ‘Larry’ −

> db.system.users.update({"user":"John"}, {$set:{"user":"Larry"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us verify the user has been created with name ‘Larry’ or not using getUser() −

> db.getUser('Larry');

This will produce the following output −

{
   "_id" : "admin.John",
   "user" : "Larry",
   "db" : "admin",
   "roles" : [
      {
         "role" : "userAdminAnyDatabase",
         "db" : "admin"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}

If you will now try to get older user name then a null value will be displayed. Let us see the same −

> db.getUser('John');

This will produce the following output −

Null

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements