Connect to MongoDB
mongosh mongodb://<host>:<port>
Change to the admin database
use admin
Modify the following command with your desired super-admin username/password.
NOTE: Role userAdminAnyDatabase grants the privilege to create other users on any existing database.
> db.createUser(
{
user: "admin",
pwd: "***********",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Disconnect from the MDB shell using Ctrl+D
Modify /etc/mongod.conf to enable auth.
security:
authorization: "enabled"
Restart MongoDB
systemctl restart mongod.service
To login use one of the following:
use the database you're authenticating against first.mongosh mongodb://<host>:<port>
> db.auth("superadmin", "thepianohasbeendrinking")
mongosh mongodb://<username>:<password>@<host>:<port>
Create a new user that has full access to a specific database
> use myDatabase
> db.createUser(
{
user: "newuser",
pwd: "*********",
roles: [ { role: "dbOwner", db: "myDatabase" } ]
}
)