These operators help you save the results of your data processing into a new or existing collection. This way, you can keep the results for later use.
$out and $merge for writing results in MongoDB
db.collection.aggregate([
{ $out: "targetCollection" }
])
// or
db.collection.aggregate([
{ $merge: { into: "targetCollection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])$out replaces the entire target collection with the aggregation results.
$merge can update existing documents or insert new ones based on matching fields.
db.sales.aggregate([
{ $match: { status: "A" } },
{ $out: "activeSales" }
])db.orders.aggregate([
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $merge: { into: "customerTotals", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])This finds all products in the 'Books' category and merges them into 'booksCollection'. Existing documents are replaced, new ones are inserted.
db.products.aggregate([
{ $match: { category: "Books" } },
{ $merge: { into: "booksCollection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])Use $out when you want to replace the whole collection with new data.
Use $merge when you want to update or add data without deleting existing documents.
Both operators require write permissions on the target collection.
$out saves aggregation results by replacing the target collection.
$merge saves results by updating or inserting documents based on matching keys.
These operators help keep processed data for future use or sharing.
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
