How to Create a User in MongoDB

Channel: Linux
Abstract: 3. Drop User in Mongodb You may also remove user from database using following command. use mydbCreate admin user in Mongodb Add user to a database D

MongoDB is a powerful document-oriented database system that can be used to store data for your web applications. It can be a little tricky to get started with, but thankfully there are a number of tools and resources available to help you get up and running.

In this blog post, we’ll show you how to create or drop users in MongoDB using the mongo shell. This tutorial includes:

  • Create admin user in Mongodb
  • Add user to a database
  • Drop user in Mongodb
1. Create Admin User in MongoDB

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 
2. Create User for a Database

You can also create database-specific users, that user will have access to that database only. You can also specify the access level for that user on 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 following command.

 db.getUsers() 
3. Drop User in Mongodb

You may also remove user from database using following command.

 use mydb 

 db.dropUser('mydbuser') 
Conclusion

In this tutorial, you have learned to create user accounts in the MongoDB server.

Ref From: tecadmin

Related articles