How to Enable Authentication and Create DB Users in MongoDB

By default authentication is not enabled within Mongo.  In this article we will show you how to enable authentication , create an account for global mongo administration and also create an account for database level authentication.

Create UserAdmin

First of all we go into the mongo shell and create our admin user.

use admin
    user: "admin",
    pwd: "password",
    roles: [ { role: "root", db: "admin" } ]

Enable Auth

Next we enable authentication via the use of the --auth  switch.

mongo --auth --config /etc/mongo.conf

You can use the following command to check to see that auth is enabled db.getUsers()

> db.getUsers()
2016-10-24T12:35:16.962+0100 Error: not authorized on test to execute command { usersInfo: 1.0 } at src/mongo/shell/db.js:1363

Create DB Users

Finally lets create another user and assign it to a single database.

use example db.createUser( { user: "example", pwd: "password", roles: [ { role: "readWrite", db: "example" } ] } )


 In order to connect to Mongo with your new user you must first install pymongo,

pip install pymongo==2.8.1

Next add the following is added to your

import mongoengine

_MONGODB_USER = 'example' _MONGODB_PASSWD = 'password' _MONGODB_HOST = '' _MONGODB_NAME = 'example' mongoengine.connect(_MONGODB_NAME, host='mongodb://%s:%s@%s:27017/%s' % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME))

Tags: Django, Database, Mongo, noSQL, PyMongo

About the Author


R Donato

Rick Donato is the Founder and Chief Editor of He currently works as an SDN/NFV Solutions Architect and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001