MongoDB Security and Authentication

Create an administrator user for the entire db server process

$ ./mongo
> use admin
> db.addUser(“theadmin”, “anadminpassword”)
We now have a user created for database admin. Note that if we have not previously authenticated, we now must if we wish to perform further operations, as there is a user in admin.system.users.

> db.auth(“theadmin”, “anadminpassword”)
We can view existing users for the database with the command:

> db.system.users.find()
Now, let’s configure a “regular” user for another database.

> use projectx
> db.addUser(“joe”, “passwordForJoe”)

Enabling Secure Mode

To enable secure mode, run the mongod process with the –auth option (or –keyFile for replica sets and sharding). You must either
(1) have added a user to the admin db before starting the server with -auth, or
(2) add the first user from a localhost connection (you cannot add the first user from a connection that is not local with respect to the mongod process).