use mydb★Switch to (and lazily create) a database.db.getMongo().getDBNames()All database names programmatically.db.dropDatabase()destroysDelete the current database and all its data.
db.createCollection("users")★Explicit create (also implicit on first insert).db.createCollection("logs", {capped:true, size:100000})Capped collection — fixed size, insertion-ordered.db.c.renameCollection("c2")Rename a collection.db.c.drop()destroysDelete the collection + its indexes.
db.c.insertOne({name:"Ada", age:36})★Insert a single document; returns its _id.db.c.insertMany([{...},{...}])★Insert many; {ordered:false} keeps going past errors.db.c.insertOne({...}, {writeConcern:{w:"majority"}})Require a majority ack before returning.
db.c.find()★All documents (batched cursor).db.c.find({status:"active"})★Equality filter — implicit AND across fields.db.c.findOne({_id: id})★First matching document, not a cursor.db.c.find({"addr.city":"Pune"})★Dot notation reaches into nested fields.db.c.find({tags:"db"})Array match — true if the array contains the value..count()→.countDocuments(q)Prefer countDocuments — count() is deprecated.
{age: {$gt:18, $lte:65}}★Comparison: $eq $ne $gt $gte $lt $lte.{status: {$in:["a","b"]}}★$in / $nin — match any / none in a list.{$and:[...]} · {$or:[...]} · {$nor:[...]}★Logical combinators; $not negates one operator.{field: {$exists:true}}★Field presence test; $type checks BSON type.{name: {$regex:/^A/, $options:"i"}}Pattern match, case-insensitive.{tags: {$all:["a","b"], $size:3}}Array must contain all values / have exact length.{items: {$elemMatch:{qty:{$gt:5}}}}★One array element must satisfy all conditions.{$expr:{$gt:["$spent","$budget"]}}Compare two fields of the same document.
db.c.find({}, {name:1, email:1})★Include only these fields (+ _id).db.c.find({}, {password:0})★Exclude fields (can't mix include/exclude).{_id:0, name:1}Suppress the _id field explicitly.{items: {$slice:5}}Return only the first N array elements.{items: {$elemMatch:{sku:"A1"}}}Project only the first matching array element.
.sort({age:-1})★-1 descending, 1 ascending..sort({age:-1, name:1})Multi-key sort, left to right..limit(20)★Cap the number of returned documents..skip(40).limit(20)★Offset pagination — slow for deep pages.
{$set:{status:"done"}}★Set fields; $unset removes them.{$inc:{views:1}} · {$mul:{price:1.1}}★Increment / multiply numeric fields.{$push:{tags:"new"}}★Append to an array; $addToSet adds if absent.{$pull:{tags:"old"}} · {$pop:{tags:1}}Remove matching / last (1) or first (-1) element.{$push:{scores:{$each:[9,8], $sort:-1, $slice:5}}}Push many, sort, and cap the array.{$rename:{old:"new"}} · {$min/$max:{...}}Rename a field / set only if lower / higher.{$set:{"items.$.qty":5}}★Positional $ updates the matched array element.{$set:{"items.$[e].qty":0}}, {arrayFilters:[{...}]}Filtered positional update of many elements.
db.c.updateOne({_id:1}, {$set:{...}})★Update the first match.db.c.updateMany({status:"a"}, {$set:{...}})★Update every match.db.c.updateOne(q, u, {upsert:true})★Insert if nothing matches.db.c.replaceOne({_id:1}, {whole:"doc"})Swap the entire document (keeps _id).db.c.findOneAndUpdate(q, u, {returnDocument:"after"})★Atomically update & return the document.db.c.updateMany(q, [{$set:{...}}])Pipeline update — compute from existing fields (4.2+).
db.c.deleteOne({_id:1})★Delete the first match.db.c.deleteMany({status:"old"})★Delete every match.db.c.findOneAndDelete(q)Atomically remove & return the document.db.c.deleteMany({})emptiesRemoves every document in the collection.
db.c.bulkWrite([{insertOne:{...}}, {updateOne:{...}}, {deleteOne:{...}}])★Mixed ops on one collection in a single round-trip.db.adminCommand({bulkWrite:1, ops:[...], nsInfo:[...]})★New in 8.0 — insert/update/delete across multiple collections in one request.bulkWrite([...], {ordered:false})Unordered lets independent ops run in parallel & continue past errors.
{$match:{status:"active"}}★Filter — put first so it can use an index.{$group:{_id:"$dept", total:{$sum:"$amt"}}}★Bucket by key & accumulate; _id:null = whole set.{$sort:{total:-1}} · {$limit:10} · {$skip:5}★Order & page the stream.{$lookup:{from:"o", localField:"_id", foreignField:"uid", as:"orders"}}★Left-outer join another collection.{$unwind:"$items"}★One output doc per array element.{$count:"n"} · {$sortByCount:"$cat"}Count docs / group-and-count in one stage.
{$project:{name:1, year:{$year:"$date"}}}★Select/compute fields; $addFields/$set adds without dropping.{$replaceWith:"$doc"} · {$replaceRoot:{...}}Promote an embedded document to top level.{$facet:{a:[...], b:[...]}}★Run multiple sub-pipelines over the same input.{$bucket:{...}} · {$bucketAuto:{...}}Group into ranges / auto-balanced buckets.{$unionWith:{coll:"archive", pipeline:[...]}}★Concatenate another collection's docs (5.1+).{$graphLookup:{...}}Recursive join — traverse hierarchies/graphs.{$documents:[{...},{...}]}Inline literal docs as a pipeline source (6.0+).{$merge:{into:"rollup"}} · {$out:"snapshot"}★Write results out; $merge upserts, $out replaces. Must be last.
{$setWindowFields:{partitionBy:"$dept", sortBy:{sal:-1}, output:{...}}}★Analytics over a window — keeps every document.output:{r:{$rank:{}}, dr:{$denseRank:{}}}★Ranking; in 8.0 null/missing handled like $sort.runTotal:{$sum:"$amt", window:{documents:["unbounded","current"]}}★Running total across the window.avg7d:{$avg:"$rev", window:{range:[-6,"current"], unit:"day"}}★Moving average over a time range.{$shift:{output:"$v", by:-1}}Previous/next row value (like SQL LAG/LEAD).{$densify:{field:"date", range:{step:1, unit:"day"}}}★Insert docs to fill gaps in a sequence (5.1+).{$fill:{output:{v:{method:"linear"}}}}Fill null/missing values (linear or carry-forward, 5.3+).
$cond:{if:{...}, then:A, else:B}★Ternary; $switch for many branches; $ifNull for defaults.$add $subtract $multiply $divide $mod $roundArithmetic expressions.$concat $toUpper $toLower $substr $split $trim★String building & slicing.$regexMatch:{input:"$s", regex:/^A/}Regex test as an expression; $regexFind extracts.$map $filter $reduce $size $slice $in★Transform / filter / fold arrays.$dateTrunc $dateAdd $dateDiff $dateToString $year★Date math & formatting.$toInt $toString $toDate $toDecimal $typeType conversion helpers.$convert:{input:"$b", to:{type:"string"}, subtype, format}8.0 adds string↔binData conversion & subtype.$let:{vars:{...}, in:{...}}Bind local variables inside an expression.
$sum $avg $min $max $count★Core numeric accumulators.$push:"$x" · $addToSet:"$x"★Collect values into an array / a set.$first $last · $top $bottom $firstN $lastNBoundary values; N-variants pick several (5.2+).$stdDevPop $stdDevSampStandard deviation accumulators.$percentile:{input:"$ms", p:[0.5,0.95,0.99], method:"approximate"}★P50/P95/P99; $median too (7.0+).$mergeObjects · $accumulator (custom JS)Merge docs / define a custom accumulator.
{$search:{index:"default", text:{query:"laptop", path:"name"}}}★Atlas full-text search (Lucene) — relevance-scored.{$searchMeta:{facet:{...}}}Facets & counts without returning documents.{$vectorSearch:{index:"vi", path:"embedding", queryVector:[...], numCandidates:100, limit:10}}★Semantic / kNN similarity search over embeddings.{$project:{score:{$meta:"vectorSearchScore"}}}Surface the relevance / similarity score.
db.c.createIndex({email:1})★Single-field ascending index.db.c.createIndex({email:1}, {unique:true})★Enforce uniqueness.db.c.createIndex({last:1, first:1})★Compound — ESR rule: Equality, Sort, Range.db.c.find(q).hint({email:1})Force a specific index.
createIndex({loc:1}, {expireAfterSeconds:3600})★TTL — auto-delete docs after N seconds (date field).createIndex({email:1}, {partialFilterExpression:{email:{$exists:true}}})Partial — index only matching docs; smaller.createIndex({phone:1}, {sparse:true})Sparse — skip docs missing the field.createIndex({"attrs.$**":1})Wildcard — index unknown/variable field names.createIndex({key:"hashed"})Hashed — for hashed shard keys / even distribution.createIndex({x:1}, {hidden:true})★Hidden — test dropping an index without dropping it (4.4+).
db.c.createIndex({location:"2dsphere"})★Required for GeoJSON proximity queries.{location:{$near:{$geometry:{...}, $maxDistance:1000}}}★Nearest-first within N metres.{location:{$geoWithin:{$centerSphere:[[lng,lat], r]}}}Points inside a shape/polygon/circle.{location:{$geoIntersects:{$geometry:{...}}}}Geometries that intersect the given shape.{$geoNear:{near:{...}, distanceField:"d", spherical:true}}Pipeline geo stage — must be first; adds distance.
db.c.createIndex({title:"text", body:"text"})★One text index per collection.db.c.find({$text:{$search:"coffee shop"}})★OR of terms; "phrase" for exact, -term to exclude.find({$text:{...}}, {score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}})Rank by relevance score.
Scalars
| Double / Int32 / Long | numeric; Long via NumberLong() |
| Decimal128 | exact decimal — money, precise finance |
| String | UTF-8 text |
| Boolean / Null | true/false; explicit null |
Structured
| Object | embedded document |
| Array | ordered list, mixed types allowed |
Identity & Time
| ObjectId | 12-byte default _id, time-ordered |
| Date | ms since epoch; ISODate() |
| Timestamp | internal replication use |
Special
| BinData | binary; subtype 4 = UUID |
| Regex / MinKey / MaxKey | pattern; comparison sentinels |
db.createCollection("u", {validator:{$jsonSchema:{...}}})★Enforce a JSON Schema on writes.$jsonSchema:{required:["email"], properties:{...}}★Required fields, types, ranges, patterns.{validationAction:"error"}Reject invalid writes ("warn" only logs).{validationAction:"errorAndLog"}8.1 — reject and log the violation.db.runCommand({collMod:"u", validator:{...}})Add/change validation on an existing collection.
db.createCollection("m", {timeseries:{timeField:"ts", metaField:"sensor", granularity:"minutes"}})★Purpose-built for sequential measurements.db.m.updateMany(...) · db.m.deleteMany(...)Ad-hoc updates/deletes on time series (7.0+).{timeseries:{...}, expireAfterSeconds:604800}Auto-expire old buckets (built-in TTL).
db.c.watch()★Real-time stream of insert/update/delete events.db.c.watch([{$match:{operationType:"insert"}}])★Filter the event stream with a pipeline.watch([], {fullDocument:"updateLookup"})Include the full post-update document.watch([], {resumeAfter: token})Resume from a saved token after disconnect.
const s = db.getMongo().startSession()★Start a client session.session.startTransaction()★Begin; do ops with {session: s}.session.commitTransaction() / .abortTransaction()★Commit or roll back atomically.session.withTransaction(async () => {...})Auto-retry helper — handles transient errors.// 8.0: $lookup allowed in txns on sharded collsBroader pipeline use inside transactions.
{writeConcern:{w:"majority"}}★Ack after a majority persist the write.{writeConcern:{w:1, j:true}}Ack after journal flush on the primary..readConcern("majority") · ("snapshot")★Read only majority-committed / a consistent snapshot..readPref("secondaryPreferred")★Route reads to secondaries to offload the primary.
db.createUser({user:"a", pwd:"p", roles:[{role:"readWrite", db:"app"}]})★Create a user with database roles.db.grantRolesToUser("a", [{role:"read", db:"logs"}])★Add roles; revokeRolesFromUser removes them.db.createRole({role:"appRW", privileges:[...], roles:[]})Custom role with fine-grained privileges.db.updateUser(...) · db.dropUser("a")Modify / remove a user.
encryptedFieldsMap:{ "db.coll":{fields:[{path:"ssn", queries:[{queryType:"equality"}]}]} }★Fields encrypted client-side, stored as BinData.queries:[{queryType:"range", min, max, precision}]★8.0 GA — range queries ($gt/$lt/$gte/$lte) on encrypted fields.db.coll.find({amount:{$gt:1000, $lt:5000}})Query encrypted numeric/date fields directly.
mongodump --uri "..." --out ./dump★Binary BSON dump of a deployment.mongorestore --uri "..." ./dump★Restore a mongodump.mongoexport --collection c --out c.jsonExport a collection to JSON/CSV.mongoimport --collection c --file c.json★Import JSON/CSV into a collection.
rs.initiate() · rs.status() · rs.add("host:27017")★Set up / inspect / grow a replica set.sh.enableSharding("db") · sh.shardCollection("db.c", {key:1})★Shard a collection on a key.sh.status()Cluster topology, chunk distribution, balancer state.db.adminCommand({moveCollection:"db.c", toShard:"s2"})★8.0 — move/unshard collections between shards.// 8.0: config shard stores app data tooEmbedded config server — fewer nodes, lower cost.
// 8.0: explain shows optimizationTimeMillisTime the planner spent choosing a plan.db.c.aggregate(p, {allowDiskUse:true})★Let heavy $group/$sort spill past the 100MB limit.db.setProfilingLevel(1, {slowms:100})Log slow ops; 8.0 profiles by execution time.db.currentOp() · db.killOp(opid)Inspect / kill a running operation.
query: $eq $gt $in $regex $exists $elemMatch $exprInsidefind()filters.update: $set $unset $inc $push $pull $addToSetInsideupdate*()modifiers.stage: $match $group $lookup $project $unwind $facetTop level of an aggregation pipeline.expr: $cond $map $concat $dateTrunc $sum $percentileInside pipeline stages; $-prefixed field = its value."$field" vs "$$var" vs "$$ROOT"Field ref / bound variable / the whole current doc.