$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.
| Category | Advanced & Diagnostic |
|---|---|
| MongoDB Version | 4.2+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $merge: { into: "<collection>", on: "<matchField>", whenMatched: "merge", whenNotMatched: "insert" } }
⚙️ Parameters
| into | Target collection, a string or { db, coll } object. |
|---|---|
| on | Field used to match existing documents; defaults to _id. |
| whenMatched | Behavior on match: merge, replace, keepExisting, or a custom pipeline. |
| whenNotMatched | Behavior 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
- Must be the final pipeline stage
- A string into auto-creates the target collection
- Defaults: whenMatched merge, whenNotMatched insert
🏷️ Related Tags
💡 Related Cases
📚 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.