Using Aggregation Framework

1. Understanding Pipeline Stages

ConceptDetail
PipelineArray of stages, each transforms documents
StreamingDocs flow stage-to-stage
Memory limit100MB per stage; use allowDiskUse: true to spill
OutputCursor (default), or $out / $merge collection
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
], { allowDiskUse: true });

2. Matching Documents

AspectDetail
Stage$match: {filter}
Index useYes if first in pipeline
Best practice$match early to reduce downstream work

3. Projecting Fields

OperatorUse
$projectReshape, include/exclude, compute
$unsetRemove fields
$set / $addFieldsAdd fields without removing others

4. Grouping Documents

AspectDetail
Stage$group: { _id, <accumulators> }
_id: nullSingle group (totals)
_id: exprGroup key (string, doc, or computed)
Accumulators$sum, $avg, $min, $max, $push, $addToSet, $first, $last, $count, $mergeObjects, $stdDev*

5. Sorting Results

AspectDetail
Stage$sort: {field: 1|-1}
Memory100MB unless $sort+$limit (top-K) or index-backed
$sortByCountSort by group count desc

6. Limiting Results

StageEffect
$limit: nPass first n docs
Combined$sort + $limit optimized to top-K

7. Skipping Results

StageNotes
$skip: nDrops first n; O(n) cost
PaginationPrefer range-based over skip for large offsets

8. Unwinding Arrays

OptionEffect
$unwind: "$arr"One doc per element
preserveNullAndEmptyArraysKeep docs with missing/empty arr
includeArrayIndexAdd element index field

9. Looking Up from Collections

FormUse
Equality join$lookup: {from, localField, foreignField, as}
Subquery / correlated$lookup: {from, let, pipeline, as}
Outer join$unwind with preserveNullAndEmptyArrays after
PerformanceIndex foreign field; small left side preferred

10. Adding Computed Fields

StageDetail
$addFieldsAdd or overwrite
$setAlias of $addFields
{ $addFields: { total: { $multiply: ["$qty", "$price"] }, taxed: { $round: [{ $multiply: ["$total", 1.08] }, 2] } } }

11. Replacing Root

StageEffect
$replaceRoot: {newRoot: expr}Promote subdoc to root
$replaceWithAlias

12. Counting Documents

StageEffect
$count: "name"Output: {name: N}
$group + $sumAlternative for grouped counts