$merge (Merge)

Last updated: 2026-10-09

$merge (Merge)

$merge writes pipeline results into a target collection (possibly another database or cluster), updating existing documents or inserting new ones by a match key. A superset of $out, it must be the final stage. Key options: into, on (match field), whenMatched, and whenNotMatched. Suits ETL, materialized views, and cross-collection sync.

CategoryAdvanced & Diagnostic
MongoDB Version4.2+
Example Languagemongosh (Shell)

📝 Syntax

{ $merge: { into: "<collection>", on: "<matchField>", whenMatched: "merge", whenNotMatched: "insert" } }

⚙️ Parameters

intoTarget collection, a string or { db, coll } object.
onField used to match existing documents; defaults to _id.
whenMatchedBehavior on match: merge, replace, keepExisting, or a custom pipeline.
whenNotMatchedBehavior when no match: insert or discard.

Returns:No documents continue; results are written to the target collection

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $merge: write customer totals into cust_stats
db.orders.aggregate([
  { $group: { _id: '$cust_id', total: { $sum: '$amount' } } },
  { $merge: {
    into: 'cust_stats',
    on: '_id',
    whenMatched: 'replace',
    whenNotMatched: 'insert'
  } }
])

Output:

// cust_stats is updated or inserted into

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $merge and $out?
A$out replaces the whole collection; $merge updates by key, appends incrementally, and supports cross-database targets.
QCan it write to another database?
AYes, via a 'db.coll' string or a { db, coll } object.
QHow are duplicate keys handled?
AwhenMatched decides: merge merges fields, replace swaps the document, keepExisting retains the original.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏