Create a compound index
Index on userId ascending and createdAt descending (`background` is ignored since MongoDB 4.2)
db.orders.createIndex({userId: 1, createdAt: -1}, {background: true})
More mongodb commands
-
db.orders.aggregate([{$match:{status:'paid'}},{$group:{_id:'$userId',total:{$sum:'$amount'}}},{$sort:{total:-1}},{$limit:10}])Top 10 users by total amount of paid orders
-
rs.printSecondaryReplicationInfo()Show how far each secondary is behind the primary
-
db.currentOp({active:true, secs_running:{$gt:5}})List operations that run longer than 5 seconds
-
mongodump --uri='mongodb://localhost:27017' --db=mydb --out=/backup/$(date +%F)Dump all collections of a database to BSON files in a dated folder
-
mongosh --eval 'rs.status().members.forEach(m=>print(m.name,m.stateStr,m.optimeDate))'Show the state and last applied optime of each member to find lagging or unhealthy secondaries