Turn array elements into separate pipeline rows.

Section: Core stages

Unwind an array

javascript
javascript
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.sku", units: { $sum: "$items.qty" } } },
  { $sort: { units: -1 } }
])
Explanation

`$unwind` is essential for analytics on nested arrays.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Core stages
Sum revenue by status
Filter first, then group and sum.
OpenIn sheetjavascriptsame section
Project computed fields
Shape output and derive new values.
OpenIn sheetjavascriptsame section
Join with another collection
Use `$lookup` for collection-to-collection joins.
OpenIn sheetjavascriptsame section
Run multiple result sets with $facet
Produce multiple related aggregations in one pipeline.
OpenIn sheetjavascript2 tag match
Bucket data for reporting
Group values into explicit ranges.
OpenIn sheetjavascript2 tag match
Count pipeline output
Return a final count after filters and transforms.
OpenIn sheetjavascript2 tag match