$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.

CategoryGrouping & Window
MongoDB Version5.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $setWindowFields: { partitionBy: <expression>, sortBy: { <field>: <1 or -1> }, output: { <field>: { <windowOperator>: ..., window: { documents: [...], range: [...] } } } } }

⚙️ Parameters

partitionByPartition expression; all documents form one partition when omitted.
sortBySort order within partitions, driving window computation order.
outputOutput 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏