Question 20 / 50
ImportantMediumConceptAggregation
What does $unwind do, and what silent behaviour should you know about?
Think about it first.
Short answer
It turns each array element into its own document, copying the parent fields. That is how you aggregate across line items. By default, documents with a missing or empty array disappear from the stream.
Why?
preserveNullAndEmptyArrays keeps those parents. Because $unwind multiplies document count, $match before $unwind is usually the difference between a fast and a slow pipeline. After unwind you $group on the element fields.
Example
db.orders.aggregate([
{ $unwind: "$items" },
{
$group: {
_id: "$items.name",
unitsSold: { $sum: "$items.quantity" }
}
}
])Interview tip
Mention empty-array documents vanishing. It is a favourite follow-up.
Common mistake
Unwinding first on a 50 million order collection, then matching status.
How did you do?