How to enable authentication in MongoDB Server?

By default, MongoDB has authentication disabled. So, after installing and starting the MongoDB you can directly access it with the following command:


Now, let’s create a root (which is super) user so that we can manage our MongoDB database and also can log in after enabling authentication.

After opening the mongo cell. Let’s list all the databases with the following command:

show dbs

The output should look like:

> show dbs
admin                      0.000GB
config                     0.000GB

local                      0.000GB

Now, let’s use the admin database.

> use admin
switched to db admin

Now we are inside admin database. All the root level users can be created inside this database. So, let’s create a root user with following query:

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

In the above query, we have defined the following things:

  1. Username: root
  2. Password: my_secured_password
  3. Role: root
  4. Database: admin

Which means, create a user root with the password my_secured_password. And assign a root level role inside admin database.

We’ve successfully created a root user. Now let’s enable authentication.

To enable authentication, you have to edit the config file which should be in /etc/mongod.conf.

You can use any tool to edit this file. I would prefer to use vim. Hence, use the following command to edit:

sudo vim /etc/mongod.conf

The above command opens the file and you have to press Insert key to make it editable.

I assume you pressed the Insert key.

Then, paste the following property:

    authorization: enabled

Now, you can save these changes with the following step:

  1. Press Esc key
  2. :!wq // It writes the changes and quits the edit mode.

Now, when you try to access MongoDB with a mongo command, you can access it but you can’t see any existing databases. Because the database is protected.

Now, you have to log in with credentials:

mongo -u root -p --autnenticationDatabase admin

After executing the above command you may prompt to enter the password.


Congratulations! You have successfully enabled authentication in the MongoDB server.

Leave a Reply

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x