In large-scale software engineering, we see problems in our implementation at every step. However, the biggest challenge remains to identify the root cause of the issues and fix them. In this article, we will learn how to implement user authentication with MongoDB and drop users in MongoDB when the user is no longer an employee of your organization. MongoDB is one of the most popular NoSQL databases. It is a document database that stores data as documents rather than tables. If you are new to MongoDB or need a refresher, read our introductory article on using MongoDB:

Advertisement

In this blog post, we’ll show you how to create an admin user and database user in MongoDB. Also, help you to drop users in MongoDB using the mongo shell.

1. MongoDB – Create Admin User

You can use the below commands to create users with admin privileges in your MongoDB server.

mongo 

 use admin 

 db.createUser(
     {
       user:"myadmin",
       pwd:"secret",
       roles:[{role:"root",db:"admin"}]
     }
  )

 exit 

Now try to connect with the above credentials through the command line.

mongo -u myadmin -p  --authenticationDatabase admin 

Once you have successfully created an admin account, you can secure the MongoDB instance by enabling the authentication.

2. MongoDB – Create Database User

First, we will create a user in our database, which will authenticate against our application. The following code snippet creates a user in the database. For example, we are creating a user account with read-write access to a database named “mydb”.

 use mydb 

 db.createUser(
    {
      user: "mydbuser",
      pwd: "mydbsecret",
      roles: ["readWrite"]
    }
 ) 

 exit 

To verify authentication use the following command. Result 1 means authentication succeeded.

 db.auth('mydbuser','mydbsecret') 

To list all users for a database, use the following command.

 db.getUsers() 

3. Drop User in Mongodb

Now that we have created a user and know how to grant them access to the collection, we need to know how to drop the user when they are no longer an employee of our organization. The following code snippet drops the user from the database.

 use mydb 

 db.dropUser('mydbuser') 

This code drops the user “mydbuser” from the database.

Conclusion

MongoDB is a highly scalable database that is perfect for big data. It is used by companies such as Uber, Spotify, and eBay. In this article, we discussed how to create and drop users in MongoDB. If you have any questions or would like to provide feedback, feel free to leave a comment below.

Share.

2 Comments

Exit mobile version