What is the Aggregation $setWindowFields stage?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

The $setWindowFields stage (MongoDB 5.0+) adds window function computation to MongoDB aggregation — similar to SQL window functions (OVER, PARTITION BY, ORDER BY). It computes values based on a "window" of documents surrounding each document, without collapsing documents into groups (unlike $group). Syntax: { $setWindowFields: { partitionBy: "$customerId", sortBy: { orderDate: 1 }, output: { runningTotal: { $sum: "$amount", window: { documents: ["unbounded", "current"] } }, movingAvg: { $avg: "$amount", window: { documents: [-2, 0] } }, rank: { $rank: {} } } } }. Window types: documents: based on number of documents relative to current ([-2, 0] = 2 before + current); range: based on value range of the sort field (["-1 day", "current"] for time-based); unbounded: from start/end of partition. Available functions: $sum, $avg, $min, $max, $count — cumulative or sliding; $rank, $denseRank — ranking within partition; $documentNumber — row number; $first, $last — first/last in window; $shift — value from N documents before/after; $linearFill, $locf — interpolation for missing values. Use cases: (1) Running totals (cumulative sales); (2) Moving averages (7-day rolling average); (3) Ranking (rank customers by spend per region); (4) Comparing a row to previous row (calculate change vs last period); (5) Fill missing time-series data.

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong MongoDB candidates.