Skip to content
LESSON 39 / 50Advancedaggregation

Materialized Views via $merge and $out

Persist complex aggregation transformations into concrete physical collections using $out (destructive overwrite) or $merge (incremental upsert updates).

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

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).

Sample BSON Documents:
Collection: db.customer_ltv_view
{
  "_id": "c1",
  "totalLtv": 12500,
  "lastUpdated": "2026-03-01"
}

$merge updates customer c1's balance incrementally without wiping out unchanged customers.

4. MQL Implementation Steps

Step 1: Incremental Materialized View using $merge
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"
    }
  }
]);
$merge updates existing documents in-place using an aggregation pipeline!

5. Critical Engineering Rules

Rule / ConstraintUnderlying 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" } }
Production Warning: The target collection in $merge must have a unique index matching the fields in the "on" clause.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •$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

Q1: Why is $merge significantly superior to $out for maintaining materialized views in production?

$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?