mongodb add user and password code example

Example 1: mongodb add user

use <your database>
db.createUser({
  user: '<some username>',
  pwd: passwordPrompt(),
  roles: [{
    role: 'readWrite',
    db: '<your database>'
  }]
})

Example 2: 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/