$setWindowFields (Set Window Fields)
Last updated: 2026-10-09
$setWindowFields (Set Window Fields)
$setWindowFields performs window computations — ranks, moving averages, running totals — over partitions and writes results back to each document. Specify output fields with window operators (like $rank, $denseRank, or accumulators), a sortBy order, and an optional window range. Think of SQL window functions.
| Category | Grouping & Window |
|---|---|
| MongoDB Version | 5.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setWindowFields: { partitionBy: <expression>, sortBy: { <field>: <1 or -1> }, output: { <field>: { <windowOperator>: ..., window: { documents: [...], range: [...] } } } } }
⚙️ Parameters
| partitionBy | Partition expression; all documents form one partition when omitted. |
|---|---|
| sortBy | Sort order within partitions, driving window computation order. |
| output | Output fields with their window operator definitions. |
Returns:Document stream with window-computed fields added
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setWindowFields: running total per region
db.sales.aggregate([
{ $setWindowFields: {
partitionBy: '$region',
sortBy: { date: 1 },
output: {
runningTotal: { $sum: '$amount', window: { documents: ['unbounded', 'current'] } }
}
} }
])
Output:
// Each sale gains a running total
{ "region": "EAST", "date": "2024-01-02", "amount": 30, "runningTotal": 30 }
📌 Notes
- At least one output field is required; sortBy and window operators drive the computation order
- Window ranges are expressed via documents or range
- Without partitionBy the whole stream is one partition
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $setWindowFields and $group?
A$group collapses a group into one document; $setWindowFields keeps every document and writes window results back onto it.
QCan it compute a moving average?
AYes, set the window from the previous 7 documents to current and use the $avg accumulator.
QHow do I write a window range?
AE.g. { documents: ['unbounded', 'current'] } spans from partition start to the current document; range defines a value interval.