0
0
MongoDBquery~5 mins

$unwind for flattening arrays in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $unwind for flattening arrays
O(n)
Understanding Time Complexity

When using $unwind in MongoDB, we want to understand how the work grows as the array size grows.

We ask: How does flattening arrays affect the number of operations?

Scenario Under Consideration

Analyze the time complexity of the following MongoDB aggregation using $unwind.

db.orders.aggregate([
  { $match: { status: "active" } },
  { $unwind: "$items" },
  { $group: { _id: "$items.productId", totalQty: { $sum: "$items.qty" } } }
])

This pipeline filters active orders, then flattens the items array so each item is a separate document, and finally groups by product ID.

Identify Repeating Operations

Look for repeated work inside the pipeline.

  • Primary operation: $unwind repeats work for each element in the items array.
  • How many times: Once per array element in each matched document.
How Execution Grows With Input

As the number of array elements grows, the work grows proportionally.

Input Size (n)Approx. Operations
10 items per documentAbout 10 operations per document
100 items per documentAbout 100 operations per document
1000 items per documentAbout 1000 operations per document

Pattern observation: The number of operations grows linearly with the number of array elements.

Final Time Complexity

Time Complexity: O(n)

This means the time to unwind grows directly with the number of elements in the arrays being flattened.

Common Mistake

[X] Wrong: "$unwind runs once per document regardless of array size."

[OK] Correct: Actually, $unwind processes each element inside the array separately, so more elements mean more work.

Interview Connect

Understanding how $unwind scales helps you explain data processing costs clearly and shows you know how MongoDB handles arrays internally.

Self-Check

"What if we replaced $unwind with $project to keep arrays as is? How would the time complexity change?"