Skip to content
LESSON 32 / 50Intermediateaggregation

$match Stage Placement & Early Filter Pushdown

Placing $match as the first stage in an aggregation pipeline enables index utilization (IXSCAN) and filters out non-matching documents before downstream processing.

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 $match stage filters documents according to specified criteria. When placed at the very start of a pipeline, $match takes advantage of collection indexes, using B-Trees to avoid full collection scans. Furthermore, filtering documents early minimizes memory consumption and CPU cycles for all subsequent stages.

2. Explain Like I'm 5 (Mental Model)

If you want to bake a cake for 5 friends with chocolate lovers, you filter out the non-chocolate recipes FIRST before buying ingredients and spending 4 hours cooking.

3. Real-World Architecture Example

Computing monthly revenue for completed European orders.

Sample BSON Documents:
Collection: db.orders
{
  "_id": "o10",
  "region": "EU",
  "status": "completed",
  "total": 450
}

Filtering { region: "EU", status: "completed" } in the first stage reduces 10,000,000 orders to 5,000 before grouping.

4. MQL Implementation Steps

Step 1: Optimal pipeline with $match at stage 1
db.orders.aggregate([
  { $match: { status: "completed", region: "EU" } }, // Stage 1: Uses compound index!
  { $group: { _id: "$product", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
]);
Leverages index on { status: 1, region: 1 }.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Index EligibilityOnly $match stages at the very beginning of a pipeline (or following $sort on an index) can use indexes.
Pushdown OptimizationMongoDB automatically pushes $match stages before $sort or $project when semantics permit.

6. Deep Dive: Why Post-$lookup or Post-$group $match Destroys Performance

If you execute a $lookup joining 1,000,000 orders with users, and then apply $match { "user.status": "active" }, the database must perform 1,000,000 join lookups before filtering! If you instead filter active users first or use a correlated $lookup pipeline, you perform only a fraction of the join operations.

// ❌ Flawed: joins 1M docs before filtering:
// [ { $lookup: ... }, { $match: { "order.date": { $gt: "2026-01-01" } } } ]
// ✅ Optimal: filters first, then joins:
// [ { $match: { "date": { $gt: "2026-01-01" } } }, { $lookup: ... } ]
Production Warning: Never place a $match after an expensive $unwind or $lookup if the filter could be evaluated earlier.

7. Architectural Trade-offs

Advantages
  • •Enables B-Tree index scans (IXSCAN) instead of reading every document from disk
  • •Drastically reduces the volume of data that subsequent blocking stages ($group, $sort) must buffer
  • •Protects against exceeding the 100MB aggregation memory ceiling
Disadvantages & Gotchas
  • •Cannot use an index if preceded by $project, $unwind, or $group stages

8. Technical Interview Questions

Q1: Can a $match stage use an index if it appears after a $project or $group stage in an aggregation pipeline?

No. An index can only be used by a $match stage if it appears at the very beginning of the pipeline (or following a $sort that shares the index). Once documents pass through $project or $group, they become transformed ephemeral memory documents disconnected from physical B-Tree on-disk indexes.

9. Staff-Level Ready Answer

"Always place $match at the start of an aggregation pipeline to leverage B-Tree indexes and prune data volume early. Any $match placed after transformative stages like $group, $project, or $unwind operates entirely in memory on unindexed ephemeral documents."

10. Quick Knowledge Check

Where must $match be placed in an aggregation pipeline to take advantage of an index scan (IXSCAN)?