How to rename a user in MongoDB?
Asked Answered
R

1

8

There is a user in database, this user should be renamed. How to rename the user? The MongoDB user management reference has method db.updateUser but I don't see how to set a new name for the user. How to update the username? ty

db.updateUser(
   "<username>",
   {
     customData : { <any information> },
     roles : [
               { role: "<role>", db: "<database>" } | "<role>",
               ...
             ],
     pwd: "<cleartext password>"
    },
    writeConcern: { <write concern> }
)
Rockbottom answered 8/2, 2016 at 8:36 Comment(0)
L
13

Did you try to update the user?

db.system.users.update({"user":"oldname"}, {$set:{"user":"newname"}})

This command requires root access to admin database.

Latchstring answered 8/2, 2016 at 9:16 Comment(7)
This way didn't try. Is your approach common why then there's db.updateUser() supported? Anyway thank you for the solution :).Barbarese
Well, off the top of my head updateUser encrypts plain passwords, and don't require access to system.users database.Latchstring
btw the command db.system.users.update({"user":"oldname"}, {$set:{"user":"newname"}}) gave error ("errmsg" : "not authorized on admin to execute command { update:) for the user with following roles roles : [ { role : "userAdminAnyDatabase", db : "admin" } ]. Had to auth as a user that has roles roles : [ { role : "root", db : "admin" } ] to successfully issue db,system.users.update(....Barbarese
Updated the answer. Thanks.Latchstring
@Willmore Alex is right, the updateUser is one of the many shell convenience method, as can be seen when issuing a db.updateUser (note the missing parenthesis. I would like to add that you don't necessarily have to be root. Any User with the role userAdmin for the authenticationDatabase (admin in this case) or userAdminAnyDatabase can do this. Be careful with the latter, the user having this role can grant any privilege to himself or others.Emulsify
Warning: it MAY matter to some, that the ID of the user will be unchanged (unsurprisingly), and that means that the old username may still be a part of that ID.Westmoreland
Meanwhile update() ist deprecated, use updateOne() instead.Tuberosity

© 2022 - 2024 — McMap. All rights reserved.