MongoDB Cheatsheet (Docker) - adonisv79/bytecommander.com GitHub Wiki
Docker installation
Basic
docker run -d --name mongo-main -p 27017:27017 mongo:latest
Secured (with initialized ROOT user and password on ENV)
docker run -d --name mongo-main -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=password mongo:latest
Volume mount(-v)
docker run -d --name mongo-main -p 27017:27017 -v /my/own/datadir:/data/db
Mongo CLI
Create user db.createUser()
The sample below creates an admin user that can read and write to any database.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
this user can connect to mongodb using the following
mongo --username myUserAdmin --password --host localhost --port 27017
ref)
Create new role for new db (The following below shows a user role with limited actions for 'any' collection on a particular db
use sauth
db.createRole({
role: "sauth_web_agent",
privileges: [
{ resource: { db: "sauth" , collection: "" }, actions: [ "find", "insert", "update" ] }
],
roles: []
})
db.createRole({
role: "sauth_event_monitor",
privileges: [
{ resource: { db: "sauth" , collection: "events" }, actions: [ "find" ] }
],
roles: []
})
db.createRole({
role: "sauth_admin",
privileges: [],
roles: [{ role: "dbOwner", db: "sauth" }]
})
Add user accounts for the roles
db.createUser(
{
user: "myusername",
pwd: "mypassword",
roles: [ { role: "sauth_admin", db: "sauth" } ]
}
)
db.createUser(
{
user: "sauthwebapp",
pwd: "somepassword",
roles: [ { role: "sauth_web_agent", db: "sauth" } ]
}
)