Using Advanced Aggregation Stages

1. Filtering Arrays in Documents

OperatorUse
$filterSubset array by condition
$mapTransform each element
$reduceAccumulate to single value
{ $addFields: { active: { $filter: { input: "$sessions", as: "s", cond: { $gt: ["$s.lastSeen", cutoff] } } } } }

2. Using $facet for Multi-Pipeline

AspectDetail
Form$facet: { name1: [stages], name2: [stages] }
EffectMultiple pipelines, single input, multi-result doc
Use caseDashboards: results + count + filters

3. Using $bucket for Categorization

FieldDescription
groupByExpression to bucket on
boundariesSorted array of bucket edges
defaultCatch-all bucket name
outputAccumulators per bucket

4. Using $bucketAuto for Auto-Bucketing

FieldDescription
groupByExpression
bucketsTarget bucket count
granularityOptional preferred series (1-2-5, R5, etc.)

5. Using $graphLookup for Recursive Queries

FieldDescription
fromTarget collection
startWithInitial value(s)
connectFromField / connectToFieldTraversal edges
asOutput array field
maxDepthRecursion cap
depthFieldAdd depth per match

6. Using $sample for Random Documents

FormEffect
$sample: {size: N}Pseudorandom N docs
PerformanceO(N) when first stage on non-sharded collection

7. Using $out to Output Collection

AspectDetail
Form$out: "coll" or {db, coll}
BehaviorAtomically replaces target collection
IndexesPreserved if same name; otherwise rebuilt

8. Using $merge to Merge Collections

FieldDescription
intoTarget coll
onMatch field(s)
whenMatchedreplace | merge | keepExisting | fail | [pipeline]
whenNotMatchedinsert | discard | fail

9. Using $redact for Access Control

System VarEffect
$$KEEPInclude subtree
$$PRUNEExclude subtree
$$DESCENDApply to nested docs

10. Using $unionWith to Combine Collections

FieldDescription
collOther collection
pipelineOptional pipeline on the other coll
OrderOriginal then unioned docs

11. Using $densify for Missing Data

AspectDetail
Form$densify: {field, range: {step, bounds, unit}}
UseInsert "gap" docs for missing time/range values
Pairs with$fill to populate values

12. Using $fill for Null Values

MethodEffect
valueConstant fill
method: "linear"Linear interpolation
method: "locf"Last observation carried forward