querydrill

Learn › Reference

MongoDB operator cheatsheet

One page, no explanations - the operators grouped by what they are for, and the pipeline shapes worth carrying in your head. Every entry is covered properly in a lesson if you need the reasoning behind it.

Querying and updating

If you forget everything else, remember these.

Arrays

Array contains value
→ { skills: "MongoDB" }

Any match
→ $in

All values required
→ $all

Multiple conditions on SAME array object
→ $elemMatch

Nested objects

"address.city": "Surat"

Updates

$set        Set field
$inc        Increment/decrement
$push       Add to array
$addToSet   Add without duplicates
$pull       Remove from array

Important distinction

$set: { address: {...} }

can replace the entire nested object

vs:

$set: {
  "address.city": "Bangalore"
}

updates only that field.

Pagination

Small/simple pagination
→ skip + limit

Large datasets
→ cursor/range-based pagination

Atomicity

Single-document operations are atomic.

find() vs aggregate()

find()
→ retrieve/filter documents

aggregate()
→ transform/process documents through stages

Aggregation stages

$match
"Which documents?"

$project
"What should each document look like?"

$set
"What field do I want to add/change?"

$unwind
"Do I need to turn array elements into individual documents?"

$group
"Do I need to combine documents?"

$sort
"In what order?"

$limit
"How many?"

$skip
"Which results should I skip?"

Advanced aggregation

JOIN COLLECTION
→ $lookup

FILTER DOCUMENTS
→ $match

FILTER ARRAY ELEMENTS
→ $filter

TRANSFORM DOCUMENT
→ $project / $set

TRANSFORM ARRAY ELEMENTS
→ $map

FLATTEN ARRAY
→ $unwind

COMBINE DOCUMENTS
→ $group

REDUCE ONE ARRAY
→ $reduce

IF / ELSE
→ $cond

DEFAULT VALUE
→ $ifNull

ARRAY LENGTH
→ $size

GET ARRAY ELEMENT
→ $arrayElemAt

MULTIPLE RESULTS / STATS
→ $facet

GROUP BY DATE
→ $year / $month / $dateToString

Patterns worth memorising

Not the syntax details - these shapes:

Pattern A — Join

Need another collection
→ $lookup

Need one joined object instead of an array
→ $unwind

Pattern B — Array transformation

Keep the array
→ $map / $filter

Pattern C — Array analytics

Need individual elements to participate
in grouping or pipeline stages

→ $unwind

Pattern D — Array → single value

items[]
↓
one calculated value

→ $reduce

Pattern E — Conditional counts/sums

$group
+
$sum
+
$cond

Pattern F — Dashboard response

Same filtered dataset
↓
Multiple calculations

→ $facet

Other reference pages

How to think about an aggregation pipeline

Common aggregation mistakes

$match vs $filter, $project vs $map, $group vs $reduce