How to Create and Drop Users in MongoDB

How to Create and Drop Users in MongoDB

 

How to Create and Drop Users in MongoDB


MongoDB is a NoSQL database server. The default installation provides you access to the database using the mongo command through the command line without authentication. In this tutorial, you will learn how to create users in the MongoDB server with proper authentications.

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

Add User for 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 on mydb database.

> use mydb

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

> exit


To verify authentication use the following command. In result 1 means authentication succeeded.

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

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

> db.getUsers()

Drop User for Database

You may also remove users from the database using the following command.

> use mydb

> db.dropUser('mydbuser')
Reactions

Post a Comment

0 Comments

close