MongoDB useful commands

Create User

  1. Connect mongodb by typing mongo
  2. Switch to admin database by typing use admin
  3. Create user and password with appropriate role. Like following
    user: "admin",
    pwd: "admin",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  1. Then disconnect from MongoDb shell by typing Ctl+D

Enable authentication

  1. Open /etc/mongod.conf with your favorite editor like vim. Eg. sudo vim /etc/mongod.conf
  2. Now enable the authorization. You may find the following:
  authorization: "disabled"

And change it to 

  authorization: "enabled"
  1. Save and restart the mongodb using sudo service mongodb restart
  2. Now you can connect to mongodb using following 
mongo mongodb://localhost:27017 -u codersathi -p

Note: You may create other users for a specific database with a specific role


use test
    user: "testuser",
    pwd: "testpassword",
    roles: [ { role: "readWrite", db: "test" } ]

This means, creating a testuser with testpassword and readWrite role for test database.

List all users from database

  1. Go to database by typing: use db_name
  2. Query like: db.getUsers()

Change the user password

db.changeUserPassword("username_to_change_pwd", passwordPrompt())

Login with username and password


mongo database_name -u username -p

Enable Remote Access MongoDb

  1. To enable remote access to mongodb we need to sent the value for bindIp in config /etc/mongod.conf

Change User Role in  MongoDb

db.updateUser( "peg",
    roles: [{role: "dbOwner", db : "peg"} ]

Login from remote machine

mongo -u username -p --authenticationDatabase authenticationDAtabaseName

List collections

show collections

Create collections


Rename collections


Insert data in collection

db.collectionName.insert({‘id’:1, ‘name’:’Virat’}) // Or we can pass any json object db.collectionName.insert(jsonObject)

Drop/Delete database

use dbname // Now delete the database using following query db.dropDatabase()

Leave a Reply

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x