Aggregation pipeline example

Top 10 users by paid order amount

db.orders.aggregate([{$match:{status:'paid'}},{$group:{_id:'$userId',total:{$sum:'$amount'}}},{$sort:{total:-1}},{$limit:10}])

tool
mongodb20 commands
tags
mongodb

More mongodb commands

  • rs.printSecondaryReplicationInfo()

    Show secondary lag and oplog window

  • db.currentOp({active:true, secs_running:{$gt:5}})

    List operations running longer than 5 seconds

  • mongodump --uri='mongodb://localhost:27017' --db=mydb --out=/backup/$(date +%F)

    Dump all collections in a database to BSON files

  • mongosh --eval 'rs.status().members.forEach(m=>print(m.name,m.stateStr,m.optimeDate))'

    Per-member state and last applied optime; spot lagging or unhealthy secondaries

  • mongosh --eval 'db.currentOp({secs_running:{$gt:5},op:{$ne:"none"}}).inprog.forEach(o=>{print(o.opid,o.secs_running,o.ns); db.killOp(o.opid)})'

    List queries running >5s with ns then killOp each; note: killOp is async, verify after

all 20 mongodb commands