Saturday, 18 October 2014

How to enable authentication in MongoDB?

I've been asked this question several times, it is simple indeed, but apparently it is causing some problems!
Here are some simple steps:
First fire mongo shell and create the user account

use admin
db.addUser('admin', '12345')
Then shutdown the server and exit:
db.shutdownServer()
exit
Then you need to start the service with --auth parameter or add auth = true entry to the config file (e.g. in /etc/mongodb.conf). You're done! To see how this works, you can lunch MongoDB shell in two way:

mongo localhost:27017/admin -u admin-p 123456

Notice the admin (which is the db name).
Alternatively you can run the shell and then authenticate there:


use admin
db.auth('admin','123456');

Also in your code, you can specify the username and password e.g. this way in your Python code:

conn = pymongo.MongoClient("mongodb://username:password@localhost:27017")