A Step-by-Step Guide on Creating a User in MongoDB

Before we begin, ensure that you have MongoDB installed on your system and that the MongoDB server is running.

Step 1: Connect to MongoDB:

Open your terminal or command prompt and connect to the MongoDB server using the mongo shell:

mongo

This will open the MongoDB shell, and you will see the > prompt.

Step 2: Switch to the Admin Database:

By default, user management operations are performed in the admin database. Switch to the admin database using the following command:

use admin

Step 3: Create a User:

To create a new user, use the db.createUser() method. Specify the username, password, and roles for the user. For example:

db.createUser( { user: "yourUsername", pwd: "yourPassword", roles: ["readWrite", "dbAdmin"] } )

Replace “yourUsername” and “yourPassword” with the desired username and password for your user. The roles array defines the user’s privileges. In this example, the user has both read and write (readWrite) and database administration (dbAdmin) privileges.

Step 4: Verify User Creation:

To confirm that the user has been created successfully, you can use the following command:

db.getUsers()

This will display a list of all users in the admin database, including the one you just created.

Step 5: Exit the MongoDB Shell:

Exit the MongoDB shell by typing:

exit

Conclusion:

Creating a user in MongoDB is a straightforward process that involves connecting to the database, switching to the admin database, and using the db.createUser() method to define the user’s credentials and privileges. Proper user management is crucial for securing your MongoDB instance and ensuring that users have the appropriate access levels for their tasks. By following these steps, you can successfully create a user in MongoDB and enhance the security of your database.