Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Terance98
Created May 21, 2020 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Terance98/f74a3dd652137229805d5f74be752ff8 to your computer and use it in GitHub Desktop.
Save Terance98/f74a3dd652137229805d5f74be752ff8 to your computer and use it in GitHub Desktop.
/**
The following is a cheat sheet about user management in MongoDB.
**/
Start mongod with the following command
//Before creating the users
> mongod
//After creating the users
> mongod --auth
Create a user with only access a particular db
> db.createUser({'user':'testuser', 'pwd':'123', roles:[ {role:'readWrite', db:"test" }]});
Create a user with different access permssions to multiple dbs
> db.createUser({user:'analyticsuser', pwd:'123', roles:[{'role':'read', 'db':'applicationdb'}, { 'role':'readWrite', 'db':'analyticsdb'}]});
Connect to mongodb with created user credentials
> mongo -u <username> -p <password> server/dbname
> eg: mongo -u testuser -p 123 localhost/test
Revoke an already existing user's access to a DB and remove his access roles
> db.revokeRolesFromUser(
"testuser",
[
{ role: "readWrite", db: "test" }
]
)
Grant the access roles back to the user
> db.grantRolesToUser(
"testuser",
[
{ role: "read", db: "test" }
]
)
Create a new custom Role
> db.createRole(
{
role: "testRole",
privileges: [
{ resource: { db: "test", collection: "children" }, actions: [ "update", "insert", "remove" ] }
],
roles: [
{ role: "readWrite", db: "test" }
]
},
{ w: "majority" , wtimeout: 5000 }
)
Execute mongo commands throught shellscripts
//use the name of the DB also while executing the scripts
> mongo my-db --eval "printjson(db.serverStatus())"
> mongo my-db --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName
> mongo my-db --eval 'db.createUser(
{
user: "accountUser",
pwd: passwordPrompt(), //or password can be predefined
roles: [ "readWrite", "dbAdmin" ]
}
)'
> mongo my-db --eval "db.certificates.find().pretty()"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment