7

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> }
)

1 Answers1

12

Did you try to update the user?

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

This command requires root access to admin database.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
  • This way didn't try. Is your approach common why then there's db.updateUser() supported? Anyway thank you for the solution :). – Developer Marius Žilėnas Feb 08 '16 at 09:51
  • Well, off the top of my head `updateUser` encrypts plain passwords, and don't require access to `system.users` database. – Alex Blex Feb 08 '16 at 09:58
  • 6
    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(.... – Developer Marius Žilėnas Feb 08 '16 at 09:59
  • Updated the answer. Thanks. – Alex Blex Feb 08 '16 at 10:12
  • @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](https://docs.mongodb.org/manual/reference/built-in-roles/#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. – Markus W Mahlberg Feb 08 '16 at 11:50
  • 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. – Ciabaros Oct 06 '20 at 05:20
  • Meanwhile `update()` ist deprecated, use `updateOne()` instead. – nonNumericalFloat Nov 04 '21 at 11:18