Using Advanced Aggregation Stages
1. Filtering Arrays in Documents
| Operator | Use |
|---|---|
| $filter | Subset array by condition |
| $map | Transform each element |
| $reduce | Accumulate to single value |
{ $addFields: { active: { $filter: { input: "$sessions", as: "s", cond: { $gt: ["$s.lastSeen", cutoff] } } } } }
2. Using $facet for Multi-Pipeline
| Aspect | Detail |
|---|---|
| Form | $facet: { name1: [stages], name2: [stages] } |
| Effect | Multiple pipelines, single input, multi-result doc |
| Use case | Dashboards: results + count + filters |
3. Using $bucket for Categorization
| Field | Description |
|---|---|
| groupBy | Expression to bucket on |
| boundaries | Sorted array of bucket edges |
| default | Catch-all bucket name |
| output | Accumulators per bucket |
4. Using $bucketAuto for Auto-Bucketing
| Field | Description |
|---|---|
| groupBy | Expression |
| buckets | Target bucket count |
| granularity | Optional preferred series (1-2-5, R5, etc.) |
5. Using $graphLookup for Recursive Queries
| Field | Description |
|---|---|
| from | Target collection |
| startWith | Initial value(s) |
| connectFromField / connectToField | Traversal edges |
| as | Output array field |
| maxDepth | Recursion cap |
| depthField | Add depth per match |
6. Using $sample for Random Documents
| Form | Effect |
|---|---|
| $sample: {size: N} | Pseudorandom N docs |
| Performance | O(N) when first stage on non-sharded collection |
7. Using $out to Output Collection
| Aspect | Detail |
|---|---|
| Form | $out: "coll" or {db, coll} |
| Behavior | Atomically replaces target collection |
| Indexes | Preserved if same name; otherwise rebuilt |
8. Using $merge to Merge Collections
| Field | Description |
|---|---|
| into | Target coll |
| on | Match field(s) |
| whenMatched | replace | merge | keepExisting | fail | [pipeline] |
| whenNotMatched | insert | discard | fail |
9. Using $redact for Access Control
| System Var | Effect |
|---|---|
| $$KEEP | Include subtree |
| $$PRUNE | Exclude subtree |
| $$DESCEND | Apply to nested docs |
10. Using $unionWith to Combine Collections
| Field | Description |
|---|---|
| coll | Other collection |
| pipeline | Optional pipeline on the other coll |
| Order | Original then unioned docs |
11. Using $densify for Missing Data
| Aspect | Detail |
|---|---|
| Form | $densify: {field, range: {step, bounds, unit}} |
| Use | Insert "gap" docs for missing time/range values |
| Pairs with | $fill to populate values |
12. Using $fill for Null Values
| Method | Effect |
|---|---|
| value | Constant fill |
| method: "linear" | Linear interpolation |
| method: "locf" | Last observation carried forward |