MongoDB Common Commands

DATABASE COMMANDS:
list databases:

show dbs

list Collections/Tables:

show collections //output every collection
OR
show tables
OR
db.getCollectionNames()

Select specific collection/table:
db.collectionName.find()

ROLES COMMANDS:
list all roles:

db.getRoles()

Create new role:

use database
db.createRole(
{
role: "manageOpRole",
privileges: [
{ resource: { cluster: true }, actions: [ "killop", "inprog" ] },
{ resource: { db: "", collection: "" }, actions: [ "killCursors" ] }
],
roles: []
}
)

db.createRole(
{
role: "mongostatRole",
privileges: [
{ resource: { cluster: true }, actions: [ "serverStatus" ] }
],
roles: []
}
)

Grant User new roles:

use database
db.grantRolesToUser(
"admin",
[
{ role: "manageOpRole", db: "admin" }
]
)

db.grantRolesToUser(
"admin",
[
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
)

USER COMMANDS:

Create User:

use database
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

Delete User:

use database
db.dropUser("myUserAdmin")

List Users and Roles:

db.getUsers()

Change password:

db.changeUserPassword("admin", "password")

Create Superuser:

use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
}
)

Create CRUD User:
use app
db.createUser(
{
user: "appadmin",
pwd: "password",
roles: [ { role: "readWrite", db: "app" }
]
}
)

Be the first to comment

Leave a Reply

Your email address will not be published.


*