How to Create and Drop Users in MongoDB

MongoDB is a non-sql database server. The default installation provides you the access of database using command line without authentication. In this tutorial I will show how to create users in Mongodb server with proper authentications.

Create Admin User

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

$ mongo

> use admin

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

> exit

Now try to connect with above credentials through command line.

$ mongo -u myadmin -p --authenticationDatabase admin

Add User for Database

You can also create database specific user, that user will only have access to that database. You can also specify access level for that user on 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 following command. In result 1 means authentication succeeded.

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

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

> db.getUsers()

Drop User for Database

You may also remove user from database using following command.

> use mydb

> db.dropUser('mydbuser')