Ch. 12 · MongoDB

MongoDB Aggregation Pipeline Stage Order

MongoDB Aggregation Pipeline Stage Order. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Pipeline stages transform the document stream. Filter and projection placement affects both semantics and processing cost.

Before you start

You should understand documents, collections and indexes. Sketch representative documents and the reads and writes they must support. MongoDB-specific examples assume a collection with the shown fields; deployment topology, permissions and existing indexes can affect the operational behavior being discussed.

The practical goal is to reason through this situation: Filter eligible records before grouping when that does not change the intended result. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Track each stage’s shape

Filters before and after grouping operate on different fields and grain.

Step 2: Reduce useful input early

Move filters only when their meaning is preserved.

Step 3: Measure intermediate cardinality

Inspect document counts and explain output at expensive stages.

Worked scenario

Filter eligible records before grouping when that does not change the intended result.

Filtering individual sales greater than 100 before grouping differs from grouping all sales and selecting customers whose total exceeds 100. A customer with two sales of 60 passes the second requirement but not the first. Performance tuning cannot exchange those meanings merely to reduce early input.

Common mistake

Moving a filter across a group can turn row conditions into aggregate conditions incorrectly.

Verify the behavior

Use that two-sale counterexample and compare intermediate and final results.

Interview exercise

Tune a reporting pipeline.

Answer and reasoning

Preserve result meaning, reduce unnecessary documents early and verify the execution plan and intermediate cardinality.

Continue learning

Compare the scenario with the MongoDB interview questions and test your understanding with the MongoDB MCQs. For terminology and implementation details, consult the reference material.

More in MongoDB

read ✓MongoDB · mid

MongoDB Bulk Writes

Batch inserts and updates with bulkWrite, choose ordered or unordered, and handle partial failures correctly.

~2 min readread →
read ✓MongoDB · mid

MongoDB Capped Collections

Use capped collections for fixed-size, insertion-ordered logs, and know why documents cannot grow.

~2 min readread →
read ✓MongoDB · hard

MongoDB Change Streams and Resume Tokens

React to inserts and updates with change streams, persist resume tokens, and handle invalidate and failover correctly.

~2 min readread →
esc