Creating a MongoDB Database and User with Permissions

  1. Connect to MongoDB usingmongosh

To begin working with MongoDB, open your terminal and connect using the MongoDB shell (mongosh): 

mongosh 

  1. Create a Database

MongoDB creates databases implicitly when you first store data in them. To switch to (and create) a database: 

If you type simply use with any name of database, database will be listed after collection. 

use TestDB 

  1. Create a User

Create a user with a username, password, and roles using the db.createUser() command: 

db.createUser({
   user: “myUser”,
   pwd: “myPassword123”,
   roles: [
     { role: “readWrite”, db: “TestDB” }
   ]
}) 

  1. Assign Permissions

You can assign multiple roles to a user to grant different levels of access. For example: 

db.createUser({
   user: “adminUser”,
   pwd: “securePass456”,
   roles: [
     { role: “readWrite”, db: “TestDB” },
     { role: “dbAdmin”, db: “TestDB” }
   ]
}) 

  1. Authenticate as the Created User

To log in using the newly created user credentials, use the following command: 

mongosh -u myUser -p myPassword123 –authenticationDatabase testDB 

 

Recent Posts