How to create a database admin that will manage its database users

username picture username · Jul 11, 2014 · Viewed 15.1k times · Source

I'm using MongoDB ver2.6.2 and want to create a database admin that will able to manage its users (add and remove them). I have two databases - admin and books. The user admin_books is supposed to be a dbOwner and be able to create and remove users from books database:

/* creating admin db */
> use admin;
switched to db admin
> db.createUser( { "user" : "admin_root", "pwd": "pass", "roles" : ["root"] } )
Successfully added user: { "user" : "admin_root", "roles" : [ "root" ] }

/* creating books db */
> use books;
switched to db books
> db.createUser( { "user" : "admin_books", "pwd": "pass", "roles" : ["dbOwner"] } )
Successfully added user: { "user" : "admin_books", "roles" : [ "dbOwner" ] }
> db.createUser( { "user" : "logger", "pwd": "pass", "roles" : ["readWrite"] } )
Successfully added user: { "user" : "logger", "roles" : [ "readWrite" ] }

I found that all users are actually stored in admin db starting from version 2.6. When I try to query db users when logging in to books db as admin_books I'm getting the following error:

> use books
switched to db books
> db.auth("admin_books", "pass")
1
> db.system.users.find()
error: { "$err" : "not authorized for query on books.system.users", "code" : 13 }

Is there any roles and privileges I need to add to admin_books to allow him to manage users? Or what would be the correct way of doing this?

I know there was a similar question, but the answer suggests to add a 'userAdminAnyDatabase' privilege to user even though the admin has to manage only single db.

Answer

Ahmed Haque picture Ahmed Haque · May 19, 2015

Not sure if this was answered straighforwardly enough but here's how you do it:

db.createUser({user: "USERNAME", pwd: "PASSWORD", roles: [{role: "dbOwner", db: "DATABASE"}]});

Where USERNAME, PASSWORD, and DATABASE are to be filled in with your fields.

http://docs.mongodb.org/manual/reference/method/db.createUser/