First steps with MongoDB: Create a real admin user

Written by - 0 comments

Published on July 24th 2013 - Listed in MongoDB DB


In the last days I've made my first steps with MongoDB, a NoSQL database application server. Having known relational databases like MySQL and PostgreSQL for quite some years now, the syntax change is huge. It's like you know how to ride a bike, but now you need to learn how to ride it backwards. Yep - it's not that easy but it's learnable.

Without going too much into detail, I had problems creating a full database admin user, like "root" in MySQL. In the official MongoDB documentation there is a section "Create a User Administrator" , but I kind of misinterpreted the chapter. I thought, that by following the steps on the documentation, I would now create a user with full administrator rights:

> use admin
switched to db admin
> db.addUser( { user: "theadmin", pwd: "mypassword", roles: [ "userAdminAnyDatabase" ] } )
{
        "user" : "theadmin",
        "pwd" : "02cdbcb825fda3c0824be229afa605e8",
        "roles" : [
                "userAdminAnyDatabase"
        ],
        "_id" : ObjectId("51f02bbccff158b61e938109")
}

But when I added "auth = true", restarted MongoDB and tested the authentication, I couldn't even list the databases:

> use admin
switched to db admin
> db.auth("theadmin","mypassword")
1
> show dbs
Wed Jul 24 21:42:47.367 JavaScript execution failed: listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:L46

The reason is pretty simple if you re-read the chapter and understand the phrase differently. "User Administrator" actually means an administrator only for administrating the users, not the databases itself.

To create a "real" database administrator user (with all rights over all databases), there are four roles essential which need to be assigned:

> db.addUser( { user: "theadmin",
... pwd: "mypassword",
... roles: [ "userAdminAnyDatabase", "readWriteAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin" ] } )

{
        "user" : "theadmin",
        "pwd" : "02cdbcb825fda3c0824be229afa605e8",
        "roles" : [
                "userAdminAnyDatabase",
                "readWriteAnyDatabase",
                "dbAdminAnyDatabase",
                "clusterAdmin"
        ],
        "_id" : ObjectId("51f02f623e8b142dc117aa76")
}

Important: The role "clusterAdmin" is also required in a single MongoDB server. So let's try it again with a new authentication:

> use admin
switched to db admin
> db.auth("theadmin","mypassword")
1
> show dbs
admin   0.203125GB
local   0.078125GB
test    0.203125GB
testdb  0.203125GB

That looks good!

I fell a couple of times off the bike already and I will continue to fall - but eventually I will learn how to master the bike. =)


Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.