MongoDB (mongosh) Cheat Sheet
Quick reference for mongosh: connect, CRUD, query operators, aggregation pipeline, indexes, replica sets, users and dump/restore — with the most common shell patterns and practical examples.
30 commands
Connect & Meta
mongosh "<uri>"Connect to MongoDB using a standard connection URI.
--quiet; --eval 'cmd'; --file script.js; --apiVersion 1/2
mongosh "mongodb://app:[email protected]:27017/app_production?authSource=admin"show dbs / use <db> / show collectionsList databases; switch to one; list collections in the current db.
show dbs | use app | show collectionsdb.serverStatus() / db.stats()Server info: connections, opcounters, replication state; db stats: size & collections.
.pretty() to pretty-print; .verbose(); .json; --eval result
db.serverStatus().connections && db.stats().dataSizeCRUD: Read
db.<coll>.find()Query a collection; chain .pretty() .limit() .skip() .sort() to shape the result.
.projection({name:1, email:1, _id:0}); .sort({createdAt:-1}); .limit(20); .skip(20); .count(); .allowDiskUse()
db.orders.find({status:'paid', amount:{$gte:10}}).sort({createdAt:-1}).limit(20).pretty()db.<coll>.findOne({...}) / db.<coll>.countDocuments({...})Read a single document, or count docs matching a filter.
findOne with/without filter; estimatedDocumentCount is O(1)
db.users.findOne({email:'[email protected]'}, {pwd:0, _id:0}) && db.orders.countDocuments({status:'paid'})CRUD: Create
db.<coll>.insertOne({...}) / insertMany([...])Insert one or many documents; options: ordered:false writes all valid docs even if one fails.
db.logs.insertMany([{k:'api', t:new Date()}, {k:'worker', t:new Date()}], {ordered:false})CRUD: Update
db.<coll>.updateOne(filter, update, opts)Update one document. Use operators like $set $inc $push $pull $addToSet $rename $unset.
upsert:true; arrayFilters:[] for nested arrays; returnDocument:'after' (findOneAndUpdate)
db.users.updateOne({email:'[email protected]'}, {$inc:{loginCount:1}, $set:{lastSeen:new Date()}}, {upsert:true})db.<coll>.updateMany(filter, update) / findOneAndUpdateUpdate many docs (write is bulk); findOneAndUpdate returns the doc pre/post update atomically.
db.orders.updateMany({status:'pending', createdAt:{$lt:new Date(Date.now()-864e5)}}, {$set:{status:'cancelled'}})CRUD: Replace
db.<coll>.replaceOne(filter, replacement)Replace entire document except _id (not allowed in replacement).
db.users.replaceOne({email:'[email protected]'}, {name:'Alice', email:'[email protected]', role:'admin', tags:['vip']})CRUD: Delete
db.<coll>.deleteOne / deleteMany(filter)Remove docs matching the filter. deleteMany({}) deletes everything (used with caution).
db.sessions.deleteMany({lastSeen:{$lt:new Date(Date.now()-7*864e5)}}) && db.orders.deleteOne({_id:ObjectId('...')})Query Operators
Comparison: $eq / $ne / $gt / $gte / $lt / $lte / $in / $ninThe standard comparison operators; $in matches a list of values.
db.orders.find({amount:{$gte:10,$lt:100}, status:{$in:['paid','shipped']}})Logical: $and / $or / $not / $norCombine predicates; $not is regex/metadata only, regex needs explicit regex.
db.products.find({$or:[{sale:true,price:{$lt:50}},{tags:'vip'}]})$exists / $type / $regex / $expr / $modField-level predicate: presence, BSON type, regex match, aggregation comparison ($expr), $mod.
db.users.find({email:{$exists:true, $regex:'@example.com$', $options:'i'}})db.<coll>.distinct(field, filter)Get unique values in a field (with optional filter).
db.orders.distinct('userId', {status:'paid'}).lengthAggregation
.aggregate([...])Build a pipeline of stages: $match → $group → $project → $sort → $limit → $lookup → $unwind → $facet.
.explain('executionStats'); allowDiskUse:true; collation document
db.orders.aggregate([ { $match:{status:'paid'} }, { $group:{_id:'$userId', gmv:{$sum:'$amount'}, n:{$sum:1}} }, { $sort:{gmv:-1} }, { $limit:50} ])$lookup / $graphLookupJoin across collections ($lookup) and recursive tree walks ($graphLookup).
db.orders.aggregate([{$lookup:{from:'users', localField:'userId', foreignField:'_id', as:'user'}}, {$unwind:'$user'}, {$project:{total:1, 'user.name':1}}])$bucket / $bucketAuto / $sample / $sortByCountUseful aggregators: bucketing, sampling, top-N counting.
db.events.aggregate([{$sample:{size:100}}, {$group:{_id:'$kind', n:{$sum:1}}}])Indexes
db.<coll>.createIndex(spec, opts)Create single/composite/geospatial/text/TTL indexes.
{unique:true, partialFilterExpression, sparse, expireAfterSeconds, weights, name}
db.users.createIndex({email:1}, {unique:true}) && db.events.createIndex({ts:1}, {expireAfterSeconds:7*86400}) && db.shops.createIndex({loc:'2dsphere'})db.<coll>.getIndexes() / dropIndex / dropIndexesList indexes; remove one / all (sometimes: just don't call this in prod!).
db.users.getIndexes().forEach(i=>print(i.name, JSON.stringify(i.key)))db.<coll>.explain('executionStats').find(filter)Inspect the winning plan & actual execution stats. Look for COLLSCAN, IXSCAN, FETCH, sort stage.
executionStats / queryPlanner / allPlansExecution; verbosity
db.orders.find({userId:42,createdAt:{$gte:new Date('2026-01-01')}}).sort({createdAt:-1}).explain('executionStats').queryPlanner.winningPlandb.<coll>.hint({...})Force the planner to use a particular index — debug bad plans, plan regressions.
db.users.find({email:'[email protected]'}).hint({email:1}).explain()Maintenance
db.runCommand({...}) / db.adminCommand / db.commandRun MongoDB commands directly. escape for operations not in the shell helper.
db.runCommand({listCollections:1, name:'app'}) && db.adminCommand({listDatabases:1}).databases.lengthdb.revokeRolesFromUser / grantRolesToUserRole management (run on admin DB).
use admin; db.createUser({user:'audit',pwd:'...',roles:[{role:'readAnyDatabase',db:'admin'}]})Replica Set
rs.initiate() / rs.status()Bootstrap a single-node replica set; show health.
rs.initiate({_id:'rs0',members:[{_id:0,host:'m1:27017'}]}); rs.status().myState
rs.initiate({_id:'rs0',members:[{_id:0,host:'m1:27017'},{_id:1,host:'m2:27017'},{_id:2,host:'m3:27017'}]})rs.add / rs.remove / rs.stepDownAdd / remove members; force election to test failover.
rs.add('m4:27017'); rs.remove('m3:27017'); rs.stepDown(60)
rs.add('m4.internal:27017') && rs.stepDown(60) && sh.status() on the next memberSharded Cluster
sh.status() / sh.enableShardingInspect the cluster topology / enable sharding on a database.
use admin; sh.enableSharding('analytics'); sh.shardCollection('analytics.events', {userId:1, ts:1})Backup & Migration
mongodump / mongorestoreLogical backup / restore. Use --uri, --db, --archive to stream; --gzip for compressed.
--gzip; --archive=file.archive; --oplog for point-in-time; --nsInclude/Exclude
mongodump --uri="mongodb://user:pw@m1:27017/?authSource=admin" --gzip --archive=/backup/app-2026-07-23.archive && mongorestore --gzip --archive=/backup/app.archive --nsInclude='app.*' --dropmongoexport / mongoimportExport / import JSON or CSV. Stays as a separator engine for piping between Mongo and other systems.
--type=json|csv; --fields=a,b,c; --headerline; -q filter; --jsonArray (single top-level array)
mongoexport --uri="..." -d app -c orders --type=json -q '{"status":"paid"}' --out=orders.json && mongoimport --drop --jsonArray orders.json -d copy -c ordersmongotop / mongostatLive monitoring: how much time each collection spent on read/write in the last second; statistics.
interval in seconds; --host
mongostat --host=m1.internal --authdb=admin --username=ops -i 5db.shutdownServer()Run on admin DB to stop mongod cleanly — also useful after rm/poweroff to recover.
use admin; db.shutdownServer({force:true}? No; clean shutdown waits for oplog replication)
use admin; db.shutdownServer()Cheatsheet version 1.0.0
Covers MongoDB 6.0+ / mongosh 1.6+