TExcelTAD
Home › MongoDB › Aggregation $unwind

Aggregation $unwind

$unwind takes an array field and outputs one document per element. Each output document is a copy of the input with the array replaced by a single element. It is the key to analysing data stored in arrays, like the line items of an order.

js
{ $unwind: '$items' }
// or, with options:
{ $unwind: { path: '$items', includeArrayIndex: 'line', preserveNullAndEmptyArrays: true } }

One document per element

Order 1005 has three line items, so $unwind turns it into three documents:

mongosh · try it yourself
db.orders.aggregate([
  { $match: { _id: 1005 } },
  { $unwind: '$items' },
  { $project: { _id: 1, product: '$items.name', qty: '$items.qty' } }
]).forEach(d => print(d));
{ _id: 1005, product: 'Pour-Over Dripper', qty: 1 }
{ _id: 1005, product: 'Paper Filters (100)', qty: 2 }
{ _id: 1005, product: 'House Blend', qty: 1 }

All three keep _id: 1005; the outputs of $unwind aren't stored anywhere, so duplicate _ids are fine.

Unwind, then group

Unwinding followed by grouping is the classic pattern for statistics over array elements. Revenue per product category, computed from the line items of non-cancelled orders:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: { $ne: 'cancelled' } } },
  { $unwind: '$items' },
  { $lookup: { from: 'products', localField: 'items.productId', foreignField: '_id', as: 'product' } },
  { $unwind: '$product' },
  { $group: {
      _id: '$product.category',
      units: { $sum: '$items.qty' },
      revenue: { $sum: { $multiply: ['$items.qty', '$items.price'] } }
  } },
  { $sort: { revenue: -1 } }
]).toArray());
[
  { _id: 'coffee', units: 16, revenue: 370.5 },
  { _id: 'equipment', units: 10, revenue: 330 },
  { _id: 'tea', units: 12, revenue: 132 },
  { _id: 'snacks', units: 22, revenue: 101 },
  { _id: 'merch', units: 2, revenue: 32 }
]

The second $unwind flattens the one-element array produced by $lookup.

Arrays of plain values

$unwind works on any array. Counting how many customers share each interest:

mongosh · try it yourself
print(db.customers.aggregate([
  { $unwind: '$interests' },
  { $group: { _id: '$interests', customers: { $sum: 1 } } },
  { $sort: { customers: -1, _id: 1 } }
]).toArray());
[
  { _id: 'coffee', customers: 6 },
  { _id: 'tea', customers: 4 },
  { _id: 'equipment', customers: 3 },
  { _id: 'snacks', customers: 3 }
]

Empty and missing arrays

By default, documents whose array is empty, null or missing produce no output at all, so Linus and Radia (with interests: []) silently vanish from the counts above. Use preserveNullAndEmptyArrays to keep them:

mongosh · try it yourself
const count = (unwind) => db.customers.aggregate([{ $unwind: unwind }, { $count: 'n' }]).toArray()[0].n;
print('default: ', count('$interests'));
print('preserve:', count({ path: '$interests', preserveNullAndEmptyArrays: true }));
default:  16
preserve: 18

Remembering the position

includeArrayIndex stores each element's position (from 0) in a new field:

mongosh · try it yourself
db.products.aggregate([
  { $match: { _id: 3 } },
  { $unwind: { path: '$tags', includeArrayIndex: 'position' } },
  { $project: { _id: 0, tags: 1, position: 1 } }
]).forEach(d => print(d));
{ tags: 'light', position: Long('0') }
{ tags: 'whole-bean', position: Long('1') }
{ tags: 'single-origin', position: Long('2') }

The index is stored as a 64-bit integer, which mongosh prints as Long('0').

Tip: $unwind multiplies documents: 1,000 orders with 10 items each become 10,000. $match before it, and when you only need a sum or count over the array, an expression like { $sum: '$items.qty' } or { $size: '$items' } is cheaper than unwinding.

Test yourself

An order has 4 line items. How many documents does $unwind: '$items' output for it?

  1. 1
  2. 4
  3. 5
  4. 0

What happens by default to documents with an empty array?

  1. They are output once with null
  2. They are dropped from the output
  3. The pipeline fails
  4. They are output with an empty array