1.$setWindowFields fundamentals
$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.
Key features
- partitionBy divides documents into independent groups the window is computed within, similar to $group's _id
- sortBy determines the order documents are considered in — required for rank/running-total style calculations
- output names the new field(s) and the window operator/expression computing each one
- window (documents or range) controls how many neighboring documents are included — default is the whole partition
- Unlike $group, the document count going in equals the document count coming out
- $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?"
Command
{ $setWindowFields: { partitionBy, sortBy, output: { <newField>: { <windowOperator>: <expr>, window? } } } }$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.