$out and $merge for writing results in MongoDB - Time & Space Complexity
When using $out and $merge in MongoDB, we want to know how the time to write results changes as the data grows.
We ask: How does the cost of saving results scale with more data?
Analyze the time complexity of the following MongoDB aggregation using $merge.
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $merge: { into: "customerTotals", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])
This groups orders by customer and writes the totals into another collection using $merge.
Look for repeated work inside the aggregation.
- Primary operation: Scanning each order document once to group by customer.
- How many times: Once per document in the input collection.
- Write operation: Writing grouped results to the target collection, once per group.
As the number of orders grows, the work to scan and group grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and writes for groups |
| 100 | About 100 reads and writes for groups |
| 1000 | About 1000 reads and writes for groups |
Pattern observation: The operations grow roughly in direct proportion to the number of input documents.
Time Complexity: O(n)
This means the time to process and write results grows linearly with the number of input documents.
[X] Wrong: "Using $merge or $out is instant and does not depend on data size."
[OK] Correct: Writing results requires touching each group or document, so more data means more work and time.
Understanding how writing results scales helps you explain performance in real projects and shows you know how MongoDB handles big data.
What if we changed $merge to update only existing documents without inserting new ones? How would the time complexity change?
Practice
$out and $merge stages in MongoDB aggregation?Solution
Step 1: Understand
$outbehavior$outwrites aggregation results by replacing the entire target collection with new data.Step 2: Understand
$mergebehavior$mergewrites results by updating existing documents or inserting new ones based on matching keys, preserving unmatched documents.Final Answer:
$outreplaces collection;$mergeupdates/inserts by keys -> Option CQuick Check:
$outreplaces,$mergemerges [OK]
$out replaces, $merge merges by keys [OK]- Thinking
$outappends data instead of replacing - Confusing
$mergewith deleting collections - Assuming
$mergealways replaces entire collection
$out in a MongoDB aggregation pipeline?Solution
Step 1: Recall
The$outsyntax$outstage requires the target collection name as a string directly, like{ $out: "collectionName" }.Step 2: Check options
{ $out: "targetCollection" } matches the correct syntax. The other options use incorrect formats such as extra objects or arrays.Final Answer:
{ $out: "targetCollection" } -> Option AQuick Check:
$outneeds collection name string [OK]
$out [OK]- Using object or array instead of string for collection name
- Trying to specify database inside
$outstage - Adding extra braces or brackets around collection name
summary collection after running it?db.sales.aggregate([
{ $group: { _id: "$category", total: { $sum: "$amount" } } },
{ $merge: { into: "summary", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])Solution
Step 1: Understand the
This groups sales by category and sums amounts, producing documents like { _id: category, total: sum }.$groupstageStep 2: Understand the
$mergestage$mergewrites results intosummarycollection, replacing documents with matching_idor inserting new ones.Final Answer:
summarycollection updated with total sales per category, replacing matches -> Option DQuick Check:
$mergeupdates or inserts by key [OK]
$merge updates matching keys, inserts new [OK]- Thinking
$mergereplaces entire collection like$out - Assuming aggregation fails without
$out - Believing collection stays unchanged after
$merge
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $out: { collection: "shippedOrders" } }
])What is the likely cause of the error?
Solution
Step 1: Check
$outsyntax$outrequires the target collection name as a string, not an object with a collection field.Step 2: Analyze error cause
Using{ collection: "shippedOrders" }causes syntax error; correct usage is{ $out: "shippedOrders" }.Final Answer:
Incorrect$outsyntax using object instead of string -> Option BQuick Check:
$outneeds string collection name [OK]
$out target, not object [OK]- Assuming
$matchcauses error - Thinking
$outrequires existing collection - Believing
$outcannot follow$match
userStats. You want to update existing documents by userId and insert new ones if missing, but keep other fields unchanged when matched. Which $merge option should you use?Solution
Step 1: Understand
whenMatchedoptionswhenMatched: "merge"updates only specified fields, keeping others unchanged;replaceoverwrites entire document.Step 2: Choose correct
To update existing documents by$mergeoptionsuserIdand insert new ones, usewhenMatched: "merge"andwhenNotMatched: "insert".Final Answer:
{ into: "userStats", on: "userId", whenMatched: "merge", whenNotMatched: "insert" } -> Option AQuick Check:
whenMatched: "merge"updates fields, inserts new [OK]
whenMatched: "merge" to update fields, not replace [OK]- Using
replacewhich overwrites entire documents - Choosing
failwhich errors on matches - Using invalid
whenNotMatchedoptions
Ready to prove it?
Pass the test and this pattern moves unknown
