How to rename a username in MongoDB?

To rename a username in MongoDB, you need to update the user document in the system.users collection using the $set operator. This operation modifies the user field while preserving all other user properties like roles and authentication mechanisms.

Syntax

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

Display Current Users

First, let's view all existing users in the database ?

use admin;
db.getUsers();
[
    {
        "_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"
        ]
    }
]

Rename Username

Now rename user 'John' to 'Larry' ?

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

Verify the Rename

Check if the user has been successfully renamed to 'Larry' ?

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

Attempting to retrieve the old username will return null ?

db.getUser('John');
null

Conclusion

The update() method with $set successfully renames MongoDB usernames while preserving all user properties. Note that the _id field retains the original username reference, but the actual username is updated.

Updated on: 2026-03-15T01:05:37+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements