Materialized Views via $merge and $out
Persist complex aggregation transformations into concrete physical collections using $out (destructive overwrite) or $merge (incremental upsert updates).
Aggregation Pipeline Multi-Stage Stream Stepper
Filter completed orders, aggregate total revenue by payment method, and sort highest first.
The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.
1. Formal Definition & Architecture Intent
The $out and $merge stages write the output documents of an aggregation pipeline directly into a physical collection. While $out completely overwrites the target collection, $merge (introduced in MongoDB 4.2) enables incremental Materialized Views by matching on an on-disk index key and performing upserts, updates, or custom merging.
2. Explain Like I'm 5 (Mental Model)
$out is like throwing away an old spreadsheet and saving a brand new file over it. $merge is like updating existing rows in the spreadsheet, adding new rows, and leaving unchanged rows untouched.
3. Real-World Architecture Example
Updating a daily materialized view of customer lifetime value (LTV).
{
"_id": "c1",
"totalLtv": 12500,
"lastUpdated": "2026-03-01"
}$merge updates customer c1's balance incrementally without wiping out unchanged customers.
4. MQL Implementation Steps
db.orders.aggregate([
{ $match: { updated_at: { $gt: new Date(Date.now() - 86400000) } } },
{ $group: { _id: "$user_id", newSpend: { $sum: "$total" } } },
{
$merge: {
into: "user_ltv",
on: "_id", // Match key on target collection
whenMatched: [
{ $set: { totalLtv: { $add: ["$totalLtv", "$$new.newSpend"] }, lastSync: new Date() } }
],
whenNotMatched: "insert"
}
}
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| $out (Destructive) | Replaces the entire target collection atomically upon completion. Drops existing indexes not recreated. |
| $merge (Incremental) | Matches documents on unique identifier (on), updating existing records and inserting new ones. |
6. Deep Dive: Real-Time Materialized Views vs Relational Snapshots
$merge enables true on-demand and scheduled Materialized Views in MongoDB. Unlike traditional SQL materialized views that require REFRESH MATERIALIZED VIEW (which often locks or re-scans the entire underlying relation), $merge can process an incremental delta stream (e.g. orders from the last hour) and update target aggregates in milliseconds.
// Simple upsert merge:
{ $merge: { into: "monthly_metrics", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }7. Architectural Trade-offs
- •Eliminates repetitive analytical aggregation queries by caching pre-computed results
- •$merge supports incremental delta updates without full-table recomputations
- •Materialized collections can have their own dedicated secondary indexes
- •$out drops target collection indexes; $merge requires pre-existing unique indexes
- •Materialized views are eventually consistent unless updated on every write
8. Technical Interview Questions
$out completely replaces the target collection, dropping existing indexes and requiring full-dataset recomputations. $merge operates incrementally: it can process a small delta (e.g. writes from the last 10 minutes) and update or insert records in the target collection in-place using an on identifier, preserving target indexes and cluster availability.
9. Staff-Level Ready Answer
"$out atomically replaces a target collection, while $merge provides incremental materialized view updates. $merge matches documents on unique keys (on), supporting in-place updates, pipeline transformations (whenMatched), and inserts (whenNotMatched) without rewriting the entire collection."
10. Quick Knowledge Check
Which aggregation stage allows incremental updates to an existing collection matching on a unique identifier?