Take the 2-minute tour ×

For the purpose of wanting to create a MongoDB database in a Capistrano task, I need to figure out how to create a new database via the MongoDB shell when MongoDB is running with auth turned on.

With auth turned on the MongoDB shell can't do anything without first authenticating, but authenticating has to happen while using the admin database as far as I'm aware. So I've been connecting to it for starters like:

sudo -u mongodb mongo admin --eval "db.auth(username, password)"

And that authenticates me for further action but...at that point I need to create the database, and a user for it in the same shell session. I can't however:

sudo -u mongodb mongo admin --eval "db.auth(username, password);use new_database"

Because use database can't be used in eval. So I've tried instead:

sudo -u mongodb mongo admin --eval "db.auth(username, password);db = connect('localhost:27017/new_database')"

And that will actually get me an instance of the new database I want created but if I try to:

sudo -u mongodb mongo admin --eval "db.auth(username, password);connect('localhost:27017/new_database').addUser(new_user, new_password)"

I get an authentication error, so apparently using the connect() command forgets that I've authenticated before.

So this is where I'm stuck, trying to create a database in one line with MongoDB using auth and an admin user.

Any suggestions on how I can do this?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

You can use db.getSiblingDB(name) to reference the new database and add a new account, eg:

mongo -u username -p password admin --eval "db.getSiblingDB('new_database').addUser('new_user', 'new_password');"

Now you should be able to authenticate from the command line using -u and -p:

mongo -u new_user -p new_password new_database
share|improve this answer
Works perfect, thanks! –  rjoll Jul 2 '12 at 18:45
@kschaper: Thanks, corrected the docs link (from the old wiki link). –  Stennie Apr 15 at 6:09

Provide the username and password as parameters to the mongo command rather than trying to authenticate using commands within the mongo shell. For example:

sudo -u mongodb mongo -u username -p password new_database
share|improve this answer
Tried that, no go. Got a "exception: login failed". Tried it a couple of different ways including fully qualified host:port/db_name etc. I think it fails because well, its authenticating to a database that doesn't exist and no users are added for. –  rjoll Jul 1 '12 at 6:29

Your Answer


