How to set Username, Password, and Roles to MongoDB Database


In this guide, we’ll show you how to set username, password, and roles to the MongoDB database. MongoDB database instance runs on localhost:27017 or 127.0.0.1:27017 when installing it on the local machine. And it does not ask for any username and password for accessing the database.

P.S Tested with MongoDB 4.4 version on Windows 10 machine.

MongoDB database/collection can be secured by setting the new username and password. Follow the below steps to secure the database with username and password. You can also define the roles of the user.

Step 1: Go to the installation directory of MongoDB:

Windows: C:\Program Files\MongoDB\Server\4.4\bin   #(it might be different in your case)

macOS:

Step 2:  Click on mongod.exe, it will start the MongoDB server.

Step 3: Now click on mongo.exe and it will open a command prompt to query/access the MongoDB database.

Now execute the following query one by one to set the username, password, and roles to the database.

Query 1: List all the available database/collection in the MongoDB:

db.adminCommand( { listDatabases: 1 } )

It gives you all the available collections.

{
        "databases" : [
                {
                        "name" : "admin",
                        "sizeOnDisk" : 40960,
                        "empty" : false
                },
                {
                        "name" : "config",
                        "sizeOnDisk" : 73728,
                        "empty" : false
                },           
                {
                        "name" : "springboot_mongodb_crud",
                        "sizeOnDisk" : 73728,
                        "empty" : false
                }
        ],
        "totalSize" : 311296,
        "ok" : 1
}

Query 2: Select your desired database/collection that you want to secure with username and password:

use springboot_mongodb_crud

Query 3: Copy and paste the below query in the command prompt to set a new username and password with roles.

db.createUser(
   {
     user: "root", // change accordingly 
     pwd: "root",  // change accordingly 
     roles: [ "readWrite", "dbAdmin" ]
   }
)

You will receive the confirmation message if the username and password successfully setup.

Successfully added user: { "user" : "root", "roles" : [ "readWrite", "dbAdmin" ] }

Query 4: Shutdown and restart your MongoDB database instance to apply the changes.

db.adminCommand( { shutdown: 1 } )

References

  1. db.createUser() – MongoDB Manual
  2. Built-In Roles – MongoDB Manual
  3. Enable Access Control – MongoDB Manual

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.