Skip to content
LESSON 35 / 50Intermediateaggregation

$unwind Array Flattening & Memory Multiplication

The $unwind stage deconstructs an array field from input documents, outputting one document for every element in the array.

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

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.

Sample BSON Documents:
Collection: db.orders
{
  "_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

Step 1: Basic array deconstruction
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.name", totalSold: { $sum: 1 } } }
]);
Emits one document per array item.
Step 2: Preserve null and empty arrays with array index tracking
db.orders.aggregate([
  {
    $unwind: {
      path: "$items",
      includeArrayIndex: "itemIndex",
      preserveNullAndEmptyArrays: true // Prevents discarding empty orders!
    }
  }
]);
preserveNullAndEmptyArrays retains parent documents that lack items.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Empty Array EliminationBy default, documents where the array is empty ([]), null, or missing are completely discarded.
Memory MultiplicationUnwinding 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 } } }
]);
Production Warning: Never unwind large arrays without filtering first.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •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

Q1: What happens to a document in an aggregation pipeline when $unwind is applied to an array field that is empty ([])?

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?