mongodb
MongoDB 6.0+ / mongosh 1.6+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()Related command cheatsheets
postgresql
Quick reference for PostgreSQL: psql client commands, DDL/DML statements, joins/aggregates, indexes, transactions and backup/restore — with common options and practical examples.
36 commands
PostgreSQL 14+
mysql
Quick reference for MySQL / MariaDB: client commands, DDL/DML statements, joins/aggregates, indexes, transactions and backup/restore — with common options and practical examples.
38 commands
MySQL 8.0+
redis cli
Quick reference for redis-cli: connection & info, key/string commands, hashes, lists, sets, sorted sets, streams, pub/sub, server management, persistence & replication and diagnostics — with common options and practical examples.
42 commands
Redis 6.2+
Trademark & Use Notice
These command-line tool cheatsheets are open community references. The names, logos, and trademarks of the tools referenced here (such as Git™, Docker™, Kubernetes®, kubectl, PostgreSQL®, MySQL®, Redis™, MongoDB®, Linux™, PowerShell™, Vim™, and others) are the property of their respective owners and are used here solely for identification and reference purposes.
All content in these cheatsheets is independently authored as a simplified, self-contained reference. It is not affiliated with, endorsed by, or sourced from any official documentation. Command listings, flag descriptions, and examples are original simplifications; for authoritative information please consult the official documentation of each tool.
Command syntax and option flags may differ across tool versions. The version tags shown reflect stable releases; behavior may differ in other versions. This cheatsheet does not imply any preference or recommendation by the trademark holders.
If a trademark or copyright owner believes that any content on this site infringes their rights, please send an email to [email protected]. Upon receiving valid proof of rights, we will modify or remove the relevant content within a reasonable period.
This website assumes no legal liability for any direct or indirect losses arising from the use of information presented on these pages.
About MongoDB
MongoDB is an open-source document database created by Dwight Merriman, Eliot Horowitz, and Kevin Ryan in 2007 and first released in 2009; the current stable line is MongoDB 7.0+ with `mongosh` 2.x as the modern shell (the legacy `mongo` was deprecated in 2022). MongoDB stores records as BSON documents (binary JSON with extra types like `Decimal128`, `Date`, `ObjectId`), grouped into collections without enforced schemas — schema design is the application's job, often with Mongoose or Prisma on the driver side. Core features include secondary indexes (single-field, compound, multikey, geospatial, text, wildcard), the aggregation framework with `$match` / `$group` / `$lookup` / `$facet` pipelines, transactions across documents since 4.0, change streams for reactive workloads, and time-series collections since 5.0. Replica sets provide high availability (automatic failover from a primary), and sharded clusters spread data across machines for horizontal scale. Use it when your data is naturally document-shaped (catalogs, content management, user profiles, event logs); reach for PostgreSQL when you need multi-row joins or strict ACID across aggregates. Always enable authentication (`--auth`) and bind only to private networks in production — the default install is unauthenticated and listens on `0.0.0.0`.
Cheatsheet version 1.0.0