Skip to content

Instantly share code, notes, and snippets.

@soardex
Last active October 5, 2022 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save soardex/5f47dc1e022697abe1400ec1601dfeb9 to your computer and use it in GitHub Desktop.
Save soardex/5f47dc1e022697abe1400ec1601dfeb9 to your computer and use it in GitHub Desktop.
MongoDB Create And Authenticate Using Users
1. Connect to mongodb instance.
~~~
mongod --port 27017 --dbpath /data/db
~~~
2. Create user:
~~~
use admin
db.createUser(
{
user: "superuser",
pwd: "superuser",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
~~~
3. Restart mongodb instance with authentication.
~~~
mongod --auth --port 27017 --dbpath /data/db
~~~
4. Create a user to manage a collection:
~~~
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
~~~
5. Update superuser to superuser role
~~~
use admin
db.updateUser(
"superuser",
{
roles: [ { role: "root", db: "admin" } ]
}
)
~~~
# MongoDB Roles
## Superuser
- root = dbOwner, userAdmin, userAdminAnyDatabase, readWriteAnyDatabase, dbAdminAnyDatabase, clusterAdmin, restore
## Database User Roles
- read
- readWrite
## Database Administration Roles
- dbAdmin
- dbOwner = readWrite, dbAdmin, userAdmin
- userAdmin
## Cluster Administration Roles
- clusterAdmin = clusterManager, clusterMonitor, hostManager
- clusterManager
- clusterMonitor
- hostManager
## Backup and Restoration Roles
- backup
- restore
## All-Database Roles
- readAnyDatabase
- readWriteAnyDatabase
- userAdminAnyDatabase
- dbAdminAnyDatabase
Reference:
https://docs.mongodb.com/v3.2/reference/built-in-roles/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment