querydrill

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

9
  1. $filter, and how it differs from $match

    MongoDB $filter keeps some elements of an array without splitting the document apart, unlike $match or $unwind.

  2. $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.

  3. $reduce

    MongoDB $reduce collapses an array to a single value using an accumulator, with $value and $this.

  4. $cond: if / else in a pipeline

    MongoDB $cond is if/else inside an aggregation pipeline, and the basis of the conditional counting pattern.

  5. $ifNull and missing fields

    MongoDB $ifNull supplies a default when a field is missing or null, so arithmetic on optional fields does not break.

  6. $size and $arrayElemAt

    MongoDB $size counts array elements and $arrayElemAt picks one out by index, including negative indexes from the end.

  7. 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.

  8. 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.

  9. The conditional aggregation pattern

    The MongoDB conditional aggregation pattern: $sum with $cond to count several categories in a single pass.

Drills

1 easy · 3 medium · 2 hard
Start reading →Skip to the drills