$setWindowFields fundamentals
coreadvanced$setWindowFields computes a value across a "window" of related documents — like the running total so far, or this row's rank within its group — while still outputting one document per input document, unlike $group which collapses documents together.
Think of it as
A $group answer is "one row per group". A $setWindowFields answer is "every row, plus something computed by looking at its neighbors" — the same distinction SQL draws between GROUP BY and a window function like SUM() OVER (...).
What we're doing: Add a running total of sales per region, ordered by date, without collapsing the individual sale documents.
- 2
- partitionBy resets the running total independently for each region — East's running total does not include West's sales.
- 3
- sortBy establishes the order "running" means — without it, there is no well-defined "so far".
- 6
- The window says: sum from the start of this partition up to and including the current document — the standard running-total window.
Why this works: Every original sale document is still present in the output, now carrying its own runningTotal value — which is what makes this different from a $group that would collapse all of a region's sales into one summary document.
Reaching for $group when the goal is a per-row running value, not a per-group summary
Wrong
Better
What you see: The individual sale documents disappear from the output, when the actual requirement was "each sale, plus its running total so far".
Why: $group is built to answer "one summary per group"; $setWindowFields is built to answer "every document, annotated with something computed across its neighbors" — picking the wrong one either loses the per-document detail or fails to compute the running value at all.
- $group
- collapses N documents into 1 per group
- original document fields are gone unless re-added
- answers "what is the total per group?"
- $setWindowFields
- keeps all N documents, one output per input
- every original field is still there
- answers "what is this row's running total / rank?"
Remember: $setWindowFields keeps one output document per input, annotated with a value computed over a window of related, ordered documents — reach for it when $group would lose the per-row detail you need.
See also: window operators for analytics · core pipeline stages

