$unwind Array Flattening & Memory Multiplication
The $unwind stage deconstructs an array field from input documents, outputting one document for every element in the array.
Aggregation Pipeline Multi-Stage Stream Stepper
Filter completed orders, aggregate total revenue by payment method, and sort highest first.
The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.
1. Formal Definition & Architecture Intent
The $unwind stage flattens array fields. For every element in an array, $unwind emits an independent copy of the parent document where the array field is replaced by that single element. It enables granular grouping, filtering, and aggregation on individual array items.
2. Explain Like I'm 5 (Mental Model)
If you have a shopping cart with 3 items (apple, banana, milk), $unwind splits your one shopping cart into 3 separate shopping carts, each holding just one item.
3. Real-World Architecture Example
Analyzing individual item sales from multi-item order receipts.
{
"_id": "o1",
"customer": "Alice",
"items": [
{
"name": "Keyboard",
"price": 100
},
{
"name": "Mouse",
"price": 50
}
]
}$unwind: "$items" emits two documents: { _id: "o1", customer: "Alice", items: { name: "Keyboard", price: 100 } } and { _id: "o1", customer: "Alice", items: { name: "Mouse", price: 50 } }.
4. MQL Implementation Steps
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: { _id: "$items.name", totalSold: { $sum: 1 } } }
]);db.orders.aggregate([
{
$unwind: {
path: "$items",
includeArrayIndex: "itemIndex",
preserveNullAndEmptyArrays: true // Prevents discarding empty orders!
}
}
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| Empty Array Elimination | By default, documents where the array is empty ([]), null, or missing are completely discarded. |
| Memory Multiplication | Unwinding an array with 1,000 items creates 1,000 documents in memory, multiplying document volume by 1,000x. |
6. Deep Dive: The Memory Multiplication Hazard of Early $unwind
If you have 100,000 documents and each has an array of 50 items, executing $unwind early expands your pipeline from 100,000 documents to 5,000,000 documents in RAM! Always apply $match filters BEFORE $unwind to prevent ballooning intermediate memory buffers.
// Filter before unwinding to minimize memory explosion:
db.orders.aggregate([
{ $match: { year: 2026 } }, // Filters down first
{ $unwind: "$items" }, // Only unwinds filtered subset
{ $match: { "items.price": { $gt: 50 } } }
]);7. Architectural Trade-offs
- •Enables granular aggregation and filtering on individual array elements
- •includeArrayIndex tracks original positioning for ordered sequence algorithms
- •Essential for relational-style joins and grouping on embedded items
- •Drastically increases document count in the pipeline, multiplying RAM and CPU consumption
- •Silently drops documents with empty or missing arrays unless preserveNullAndEmptyArrays is true
8. Technical Interview Questions
By default, the document is completely dropped from the pipeline. To keep documents with empty, null, or missing arrays, you must use the expanded syntax with preserveNullAndEmptyArrays: true.
9. Staff-Level Ready Answer
"$unwind deconstructs an array field, emitting a separate copy of the parent document for each array element. By default, empty or null arrays are discarded unless preserveNullAndEmptyArrays: true is configured. Because $unwind multiplies document counts, always place $match filters before $unwind to avoid memory explosion."
10. Quick Knowledge Check
Which option in the expanded $unwind syntax prevents documents with empty arrays from being deleted from the pipeline?