MongoDB Cheat Sheet

Jul 09, 2024

Related to:: MongoDB

MongoDB Shell - Mongosh

Connect to a Local Instance

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


List All Users

use admin

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
    user: "mainUserName",
    pwd:  "secret123", 
    roles: [ 
        { role: "read", db: "mainDatabaseName" },
        { role: "readWrite", db: "secondaryDatabaseName" },

RS - Replica Sets

Check Which Server is the Master


Get the Status of the ReplicaSet


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

Graph View