Learn › Advanced aggregation
Array and conditional expressions
$filter, $map, $reduce, $cond, $ifNull — working inside a document, not across documents.
By the end: Transform arrays and handle missing fields without leaving the document.
Lessons
- $filter, and how it differs from $match
MongoDB $filter keeps some elements of an array without splitting the document apart, unlike $match or $unwind.
- $map, and how it differs from $unwind
MongoDB $map transforms every element of an array in place, keeping the document intact. The $unwind you often do not need.
- $reduce
MongoDB $reduce collapses an array to a single value using an accumulator, with $value and $this.
- $cond: if / else in a pipeline
MongoDB $cond is if/else inside an aggregation pipeline, and the basis of the conditional counting pattern.
- $ifNull and missing fields
MongoDB $ifNull supplies a default when a field is missing or null, so arithmetic on optional fields does not break.
- $size and $arrayElemAt
MongoDB $size counts array elements and $arrayElemAt picks one out by index, including negative indexes from the end.
- When you do not need $unwind
When you do not need $unwind in MongoDB: compute inside the document with $map, $filter and $sum instead of flattening it.
- Filter an array, then calculate
A common MongoDB pattern: $filter an array down to the elements you care about, then $map and $sum over just those.
- The conditional aggregation pattern
The MongoDB conditional aggregation pattern: $sum with $cond to count several categories in a single pass.