MongoDB: setup Authentication

nguyennamdsn | Aug. 15, 2023, 4:39 p.m.

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 } )


Refer: How to set Username, Password, and Roles to MongoDB Database - Websparrow



0
0

Leave a comment:

Comments: