- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements