How to Create and Drop Users in MongoDB

MongoDB is a nosql database server. The default installation provides you the access of database using mongo command through command line without authentication. In this tutorial you will learn 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:"myadmin",        pwd:"secret",        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 users, that user will have access to that database only. 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') 

Thanks for Visit Here

Comments