connect to mongodb with username and password code example

Example 1: connect to mongodb with username and password

->First run mongoDB on terminal using
mongod

->now run mongo shell use following commands

    use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

->Re-start the MongoDB instance with access control.
mongod --auth

->Now authenticate yourself from the command line using
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

->You can read it from
https://docs.mongodb.com/manual/tutorial/enable-authentication/

Example 2: mongodb add admin user

use admin
db.createUser({
  user: "username",
  pwd: "password",
  roles: [ "root" ]
})

Tags:

Misc Example