Some useful MongoDB commands

Connection

Connect to node
mongo {Host}:{Port}/{DB} -u {User} -p{Password}

Sample: 
mongo localhost:27017/admin -u root -pPassword
mongo 127.0.0.1:27017/admin -u root -pPassword
Check connection status
db.serverStatus().connections
Check connection count group by IP address
db.currentOp(true).inprog.reduce(
  (accumulator, connection) => {
    ipaddress = connection.client ? connection.client.split(":")[0] : "Internal";
    accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1;
    accumulator["TOTAL_CONNECTION_COUNT"]++;
    return accumulator;
  },
  { TOTAL_CONNECTION_COUNT: 0 }
)

WiredTiger

Check WT cache status
db.serverStatus().wiredTiger.cache
Check WT available ticket status
db.serverStatus().wiredTiger.concurrentTransactions

Replication

Check replication members and their status
rs.status()
Check replication lags of nodes
rs.printSlaveReplicationInfo()
Check oplog size and log length in hours
rs.printReplicationInfo()
Check replication configuration
rs.config()
Failover to secondary/another node
# Run on PRIMARY Node
rs.stepDown()
Freeze slave node from becoming a master during the failover
# Run on SECONDARY node which need to freeze 
rs.freeze(no of seconds)

Profiling

Check Profiling Status
db.getProfilingStatus()
Enable Profiling
db.setProfilingLevel(1, { slowms: 100, sampleRate: 1 })
Disable Profiling
db.setProfilingLevel(0, { slowms: 100, sampleRate: 1 })

mtools

mongostat
mongostat -h {HostName/IP} -u {User} -p '{Password}' --port={Port} --authenticationDatabase=admin

Sample:
mongostat -h 127.0.0.1 -u root -p 'Password' --port=27018 --authenticationDatabase=admin
mongotop
mongotop -h {HostName/IP} -u {User} -p '{Password}' --port={Port} --authenticationDatabase=admin

Sample:
mongotop -h 127.0.0.1 -u root -p 'Password' --port=27018 --authenticationDatabase=admin
mlogfilter
# Get the list of collection scan whole collections 
mlogfilter mongod.log --planSummary=COLLSCAN

# Get the list of slow queries more than 1000ms
mlogfilter mongod.log --slow 1000

# Get the list of errors, warnings 
mlogfilter mongod.log  --word assert warning errors

# Get the specific namespace queries which are running more than 1000ms
mlogfilter mongod.log --namespace admin.\$cmd --slow 1000
mloginfo
mloginfo mongod.log  --queries

Shard

Check shard status
sh.status()
Stop Balancer
sh.stopBalancer()
Start Balancer
sh.startBalancer()

Note: We will keep updating this page, as long as we will have some new commands.

Leave a Reply