Learn › Aggregation
Arrays in a pipeline
$unwind: one document per array element, and the pattern it unlocks.
By the end: Aggregate over values buried inside arrays.
Lessons
- Why $group cannot see inside arrays
Why MongoDB $group cannot reach values inside an array, and the shape of the problem $unwind exists to solve.
- $unwind
MongoDB $unwind turns one document with an N-element array into N documents, so later stages can work on each element.
- $unwind + $group
The $unwind then $group pattern: flatten an array, then aggregate its elements. The most reusable pipeline in MongoDB.
- Worked example: revenue per product
A worked MongoDB aggregation: revenue per product from order line items, using $match, $unwind, $group and $multiply.