Skip to content

Latest commit

 

History

History
90 lines (88 loc) · 2.3 KB

CreateMongoDBUser.md

File metadata and controls

90 lines (88 loc) · 2.3 KB

How to Create MongoDB Super User

  • If Authorization is Enable then Disable it by commenting below code
sudo nano /etc/mongod.conf
#security:
  #authorization: enabled
  • Restart MongoDB
sudo service mongod restart
  • Connect to MongoDB shell
mongosh
  • Show database
show dbs
  • Change to admin database
use admin
  • Create superuser with all privileges
Syntax:- db.createUser({user: "username" , pwd: passwordPrompt() , roles: ["root"]})
Example:- db.createUser({user: "superuser" , pwd: passwordPrompt() , roles: ["root"]})
  • Verify Users
show users
  • If Authorization is Disable then Enable it by removing comments from below code
sudo nano /etc/mongod.conf
security:
  authorization: enabled
  • Restart MongoDB
sudo service mongod restart
  • Access Mongo Shell as Super User:
Syntax:- mongosh --port 27017 --authenticationDatabase "database_name_where_user_stored" -u "username" -p "password"
Example:- mongosh --port 27017 --authenticationDatabase "admin" -u "superuser" -p "Hello123456"
  • To Make Connection use:
Syntax:- mongodb://username:password@IP_Address:27017/database_name
Example:- mongodb://superuser:[email protected]:27017/blogdb

How to Create MongoDB User and Assign to a Database

  • Connect to MongoDB shell
- If Authorization Disable
    mongosh

- If Authorization Enable and have Superuser (Recommended)
    mongosh --port 27017 --authenticationDatabase "admin" -u "superuser" -p "Hello123456"
  • Show database
show dbs
  • Create New Database
Syntax:- use database_name
Example:- use blogdb
  • Create New User
Syntax:- db.createUser({user:"username", pwd:passwordPrompt(), roles:[{role:"readWrite", db:"database_name"}]})
Example:- db.createUser({user:"rahul", pwd:passwordPrompt(), roles:[{role:"readWrite", db:"blogdb"}]})
  • Verify Users
show users
  • Access Mongo Shell as User:
Syntax:- mongosh --port 27017 --authenticationDatabase "database_name_where_user_stored" -u "username" -p "password"
Example:- mongosh --port 27017 --authenticationDatabase "blogdb" -u "rahul" -p "Hello123456"
  • To Make Connection use:
Syntax:- mongodb://username:password@IP_Address:27017/database_name
Example:- mongodb://rahul:[email protected]:27017/blogdb