MongoDB Cheat Sheet

Jul 09, 2024

Related to:: MongoDB

MongoDB Shell - Mongosh

Connect to a Local Instance

mongosh --port 27017  --authenticationDatabase "admin" -u "adminUser"

Users

List All Users

use admin
db.system.users.find()

Create a User

The most used roles are: read, readWrite, dbAdmin, userAdmin and clusterMonitor (see the full list at Built-In Roles - MongoDB Manual v7.0)

use admin
db.createUser({
    user: "mainUserName",
    pwd:  "secret123", 
    roles: [ 
        { role: "read", db: "mainDatabaseName" },
        { role: "readWrite", db: "secondaryDatabaseName" },
    ]
})

RS - Replica Sets

Check Which Server is the Master

db.runCommand("ismaster")

Get the Status of the ReplicaSet

rs.status();

Change the Master

While connected to the master, the following could be run to make member 2 of the RS become the master. The idea is to make all the secondaries a 0.5 priority and the master 1. If we have more than 3 servers, we can follow the same principle for the other servers.

cfg = rs.conf()
cfg.members[0].priority = 0.5
cfg.members[1].priority = 0.5
cfg.members[2].priority = 1
rs.reconfig(cfg)

Graph View