What is the MongoDB Aggregation $merge and $out stage?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

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.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex MongoDB answers easy to follow.