MongoDB Admin

Set/reset admin password
  1. Make sure authentication is disabled in /etc/mongod.conf by setting security authorization: disabled or comment it out.

  2. Restart MongoDB using sudo service mongod restart

  3. Access the mongo shell commands using the terminal command mongosh this will start an interactive shell session.

  4. Type db.getSiblingDB("admin").changeUserPassword("root", "PASSWORD") and change PASSWORD to your choice, please use a random password with special characters.

  5. Type exit to exit the mongo shell.

  6. Enable authentication in /etc/mongod.conf by setting security authorization: enabled

  7. Restart MongoDB again sudo service mongod restart

Mongo shell authentication

If authentication is enabled you need to login to mongodb in the terminal using this.

mongosh -u root -p PASSWORD

Replace PASSWORD with the root mongo password.

Add user to database
  1. Change USER to username and both DATABASE to your database name.

  2. db.getSiblingDB("admin").grantRolesToUser( "USER", [ { role: "dbAdmin", db: "DATABASE" }, { role: "readWrite", db: "DATABASE" } ] )

Last updated