What is the MongoDB Aggregation $merge and $out stage?
Answer
$out and $merge are output stages that write aggregation results to a collection rather than returning them to the caller. $out: replaces an entire collection with the aggregation results. Atomically: aggregates, writes to a temp collection, then renames to the target (old collection is replaced). All or nothing — either the whole output succeeds or the original collection is untouched. Limitations: can't output to a sharded collection; creates or replaces the target collection; must be the last stage. { $out: "monthly_revenue_summary" }. $merge (MongoDB 4.2+): more flexible — can merge results into an existing collection with configurable behavior. Options: { $merge: { into: "summary", on: "_id", whenMatched: "merge", whenNotMatched: "insert" } }. on: the field(s) to match against existing documents (like a primary key for the merge). whenMatched: what to do when a document with the same "on" key exists: "replace" (replace existing), "keepExisting" (don't update), "merge" (merge new fields into existing), "fail" (throw error), [custom pipeline] (transform the matched document). whenNotMatched: "insert" (insert new document) or "discard" (ignore). Use cases for $merge: incremental updates (add daily data to monthly summary without recomputing all history), upsert from aggregation (update a cache collection), maintaining denormalized views, real-time dashboards updated by change streams + $merge.
Previous
How does MongoDB handle index builds on large collections?
Next
What are MongoDB Atlas Search and Vector Search?
More MongoDB Questions
View all →- Advanced How does MongoDB replication work internally?
- Advanced How does MongoDB sharding distribute data internally?
- Advanced What is the WiredTiger cache and how does it affect performance?
- Advanced What is the Aggregation $setWindowFields stage?
- Advanced How does MongoDB handle index builds on large collections?