How do you change MongoDB user permissions?

Ed Norris picture Ed Norris · May 13, 2013 · Viewed 37.2k times · Source

For instance, if I have this user:

> db.system.users.find()
{ "user" : "testAdmin", "pwd" : "[some hash]", "roles" : [ "clusterAdmin" ], "otherDBRoles" : { "TestDB" : [ "readWrite" ]  } }

And I want to give that user the dbAdmin permissions on the TestDB database, I can remove the user record then add it back with the new permissions:

> db.system.users.remove({"user":"testAdmin"})
> db.addUser( { user: "testAdmin",
                  pwd: "[whatever]",
                  roles: [ "clusterAdmin" ],
                  otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] } } )

But that seems hacky and error-prone.

And I can update the table record itself:

> db.system.users.update({"user":"testAdmin"}, {$set:{ otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] }}})

But I'm not sure if that really creates the correct permissions - it looks fine but it may be subtly wrong.

Is there a better way to do this?

Answer

Vaibhav picture Vaibhav · Apr 28, 2015

If you want to just update Role of User. You can do in the following way

db.updateUser( "userName",
               {

                 roles : [
                           { role : "dbAdmin", db : "dbName"  },
                           { role : "readWrite", db : "dbName"  }
                         ]
                }
             )

Note:- This will override only roles for that user.