定义
版本 5.0 中的新增功能。
对集合中指定范围的文档(称为窗口)执行操作,并根据所选 窗口操作符返回结果。
例如,您可以使用 $setWindowFields 阶段来输出:
- 集合中两个文档之间的销售额差异。 
- 销售排名。 
- 累计销售总额。 
- 分析复杂的时间序列信息,而无需将数据导出到外部数据库。 
语法
$setWindowFields 阶段语法:
{    $setWindowFields: {       partitionBy: <expression>,       sortBy: {          <sort field 1>: <sort order>,          <sort field 2>: <sort order>,          ...,          <sort field n>: <sort order>       },       output: {          <output field 1>: {             <window operator>: <window operator parameters>,             window: {                documents: [ <lower boundary>, <upper boundary> ],                range: [ <lower boundary>, <upper boundary> ],                unit: <time unit>             }          },          <output field 2>: { ... },          ...          <output field n>: { ... }       }    } } 
$setWindowFields 阶段采用包含以下字段的文档:
| 字段 | 必要性 | 说明 | 
|---|---|---|
| Optional | 指定用于对文档进行群组的表达式。在 | |
| 指定分区中用于对文档进行排序的字段。使用与  | ||
| 必需 | 指定要附加到 字段可以包含点来指定嵌入式文档字段和大量字段。 
 | |
| Optional | ||
| Optional | 一个窗口,其中的上下界是相对于从集合中读取的当前文档的位置指定的。 窗口边界是使用包含下限和上限字符串或整数的双元素数组指定的。使用: 
 | |
| Optional | 在该窗口中,使用基于当前文档中 sortBy字段的范围值来定义下边界和上边界。 窗口边界是使用包含下限和上限字符串或数字的双元素数组指定的。使用: 
 | |
| Optional | 
 | 
提示
行为
$setWindowFields 阶段会向现有文档添加新字段。可以在聚合操作中包含一个或多个 $setWindowFields 阶段。
从 MongoDB 5.3 开始,可以将 $setWindowFields 阶段与事务和 "snapshot" 读关注结合使用。
$setWindowFields 阶段不保证返回文档的顺序。
窗口运算符
这些操作符可与 $setWindowFields 阶段一起使用:
- 累加器操作符: - $addToSet、- $avg、- $bottom、- $bottomN、- $concatArrays、- $count、- $covariancePop、- $covarianceSamp、- $derivative、- $expMovingAvg、- $firstN、- $integral,- $lastN,- $max,- $maxN,- $median,- $min,- $minN,- $percentile,- $push,- $setUnion,- $stdDevSamp,- $stdDevPop,- $sum,- $top、- $topN。
- 缝隙填充操作符: - $linearFill和- $locf。
- 等级操作符: - $denseRank、- $documentNumber和- $rank。
限制
$setWindowFields 阶段的限制:
- 在 MongoDB 5.3 之前,无法使用 - $setWindowFields阶段:- 在事务内。 
- 带有 - "snapshot"读关注。
 
- 对于以下情况,sortBy 是必需的: - $linearFill操作符。
 
- 这些操作符使用隐式窗口,如果您指定了窗口选项,它们会返回错误: 
- 对于范围窗口,窗口中只包含指定范围内的数字。不包括缺失值、未定义值和 - null值。
- 对于时间范围窗口: - 窗口中只包含日期和时间类型。 
- 数值边界值必须为整数。例如,您可以使用 2 小时作为边界,但不能使用 1.5 小时。 
 
- 对于空窗口或具有不兼容值的窗口(例如,对字符串使用 - $sum),返回值取决于操作符:
示例
创建cakeSales集合,其中包含加利福尼亚州 ( CA ) 和华盛顿州 ( WA ) 的蛋糕销售情况:
db.cakeSales.insertMany( [    { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),      state: "CA", price: 13, quantity: 120 },    { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),      state: "WA", price: 14, quantity: 140 },    { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),      state: "CA", price: 12, quantity: 145 },    { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),      state: "WA", price: 13, quantity: 104 },    { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),      state: "CA", price: 41, quantity: 162 },    { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),      state: "WA", price: 43, quantity: 134 } ] ) 
以下示例使用 cakeSales 集合。
文档窗口示例
使用文档窗口获取每个州的累计数量。
此示例使用 $setWindowFields 中的文档为每个 state 输出累计蛋糕销售额 quantity:
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: "$state",          sortBy: { orderDate: 1 },          output: {             cumulativeQuantityForState: {                $sum: "$quantity",                window: {                   documents: [ "unbounded", "current" ]                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$state"按- state对集合中的文档进行分区。- CA和- WA都有分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:
在此示例输出中,CA 和 WA 的累积 quantity 数组会显示在 cumulativeQuantityForState 字段中:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162, "cumulativeQuantityForState" : 162 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120, "cumulativeQuantityForState" : 282 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145, "cumulativeQuantityForState" : 427 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134, "cumulativeQuantityForState" : 134 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104, "cumulativeQuantityForState" : 238 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140, "cumulativeQuantityForState" : 378 } 
使用文档窗口获取每年的累计数量
此示例使用 $setWindowFields 中的文档窗口输出 orderDate 中每个 $year 的累计蛋糕销售 quantity:
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: { $year: "$orderDate" },          sortBy: { orderDate: 1 },          output: {             cumulativeQuantityForYear: {                $sum: "$quantity",                window: {                   documents: [ "unbounded", "current" ]                }             }          }       }    } ] ) 
在示例中:
- partitionBy: { $year: "$orderDate" }按- orderDate中的- $year对集合中的文档进行分区。分别有- 2019、- 2020和- 2021的分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:
在此示例输出中,每年的累计 quantity 显示在 cumulativeQuantityForYear 字段中:
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134, "cumulativeQuantityForYear" : 134 } { "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162, "cumulativeQuantityForYear" : 296 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104, "cumulativeQuantityForYear" : 104 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120, "cumulativeQuantityForYear" : 224 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145, "cumulativeQuantityForYear" : 145 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140, "cumulativeQuantityForYear" : 285 } 
使用文档窗口获取每年的移动平均数量
此示例使用 $setWindowFields 中的文档窗口来输出蛋糕销售 quantity 的移动平均值:
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: { $year: "$orderDate" },          sortBy: { orderDate: 1 },          output: {             averageQuantity: {                $avg: "$quantity",                window: {                   documents: [ -1, 0 ]                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$orderDate"按- orderDate中的- $year对集合中的文档进行分区。分别有- 2019、- 2020和- 2021的分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:
在此示例输出中,移动平均数量 (quantity) 显示在 averageQuantity 字段中:
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134, "averageQuantity" : 134 } { "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162, "averageQuantity" : 148 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104, "averageQuantity" : 104 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120, "averageQuantity" : 112 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145, "averageQuantity" : 145 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140, "averageQuantity" : 142.5 } 
使用文档窗口获取每年的累计数量和最大数量
此示例使用 $setWindowFields 中的文档窗口输出 orderDate 中每个 $year 的累积和最大蛋糕销售 quantity 值:
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: { $year: "$orderDate" },          sortBy: { orderDate: 1 },          output: {             cumulativeQuantityForYear: {                $sum: "$quantity",                window: {                   documents: [ "unbounded", "current" ]                }             },             maximumQuantityForYear: {                $max: "$quantity",                window: {                   documents: [ "unbounded", "unbounded" ]                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$orderDate"按- orderDate中的- $year对集合中的文档进行分区。分别有- 2019、- 2020和- 2021的分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:- 将 - cumulativeQuantityForYear字段设置为每年的累积- quantity。
- 使用在文档窗口中运行的 - $sum操作符计算累积- quantity。- 该窗口包含介于 - unbounded下限和- current文档之间的文档。这意味着- $sum将返回分区开头和当前文档之间的文档的累积数量。
- 将 - maximumQuantityForYear字段设置为每年的最高量 (- quantity)。
- 使用在文档窗口中运行的 - $max操作符,计算所有文档的最大- quantity。- 该窗口包含介于 - unbounded下限和- upper上限之间的文档。这意味着- $max会返回分区中文档的最大数量。
 
在此示例输出中,累计 quantity 显示在 cumulativeQuantityForYear 字段中,最大 quantity 显示在 maximumQuantityForYear 字段中:
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134,   "cumulativeQuantityForYear" : 134, "maximumQuantityForYear" : 162 } { "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162,   "cumulativeQuantityForYear" : 296, "maximumQuantityForYear" : 162 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104,   "cumulativeQuantityForYear" : 104, "maximumQuantityForYear" : 120 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120,    "cumulativeQuantityForYear" : 224, "maximumQuantityForYear" : 120 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145,   "cumulativeQuantityForYear" : 145, "maximumQuantityForYear" : 145 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140,   "cumulativeQuantityForYear" : 285, "maximumQuantityForYear" : 145 } 
范围窗口示例
此示例使用 $setWindowFields 中的范围窗口,返回当前文档 price 值正负 10 美元以内的订单所售蛋糕 quantity 值的总和:
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: "$state",          sortBy: { price: 1 },          output: {             quantityFromSimilarOrders: {                $sum: "$quantity",                window: {                   range: [ -10, 10 ]                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$state"按- state对集合中的文档进行分区。- CA和- WA都有分区。
- sortBy: { price: 1 }按- price升序 (- 1) 对每个分区中的文档进行排序,因此最低的- price位于最前面。
- output将- quantityFromSimilarOrders字段设置为范围窗口中文档的- quantity值的总和。
在此示例输出中,窗口中文档的 quantity 值的总和显示在 quantityFromSimilarOrders 字段中:
{ "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145, "quantityFromSimilarOrders" : 265 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120, "quantityFromSimilarOrders" : 265 } { "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162, "quantityFromSimilarOrders" : 162 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104, "quantityFromSimilarOrders" : 244 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140, "quantityFromSimilarOrders" : 244 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134, "quantityFromSimilarOrders" : 134 } 
时间范围窗口示例
使用具有正上界的时间范围窗口
以下示例在 $setWindowFields 中使用了具有正上界时间范围单位的窗口。管道输出与指定时间范围匹配的每个 state 的 orderDate 值的数组。
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: "$state",          sortBy: { orderDate: 1 },          output: {             recentOrders: {                $push: "$orderDate",                window: {                   range: [ "unbounded", 10 ],                   unit: "month"                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$state"按- state对集合中的文档进行分区。- CA和- WA都有分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:
- 该窗口包含在 - unbounded下限和使用时间范围单位将上限设置为- 10(当前文档的- orderDate值之后 10 个月)之间的文档。
- $push返回分区起始和满足如下条件的文档之间文档的- orderDate值的数组:- orderDate值在当前文档的- orderDate值(含)加上- 1010 个月范围内。
在此示例输出中,CA 和 WA 的 orderDate 值数组显示在 recentOrders 字段中:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162,   "recentOrders" : [ ISODate("2019-05-18T16:09:01Z") ] } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120,   "recentOrders" : [ ISODate("2019-05-18T16:09:01Z"), ISODate("2020-05-18T14:10:30Z"), ISODate("2021-01-11T06:31:15Z") ] } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145,   "recentOrders" : [ ISODate("2019-05-18T16:09:01Z"), ISODate("2020-05-18T14:10:30Z"), ISODate("2021-01-11T06:31:15Z") ] } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134,   "recentOrders" : [ ISODate("2019-01-08T06:12:03Z") ] } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104,   "recentOrders" : [ ISODate("2019-01-08T06:12:03Z"), ISODate("2020-02-08T13:13:23Z") ] } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140,   "recentOrders" : [ ISODate("2019-01-08T06:12:03Z"), ISODate("2020-02-08T13:13:23Z"), ISODate("2021-03-20T11:30:05Z") ] } 
使用具有负上界的时间范围窗口
以下示例在 $setWindowFields 中使用了具有负上界时间范围单位的窗口。管道输出与指定时间范围匹配的每个 state 的 orderDate 值的数组。
db.cakeSales.aggregate( [    {       $setWindowFields: {          partitionBy: "$state",          sortBy: { orderDate: 1 },          output: {             recentOrders: {                $push: "$orderDate",                window: {                   range: [ "unbounded", -10 ],                   unit: "month"                }             }          }       }    } ] ) 
在示例中:
- partitionBy: "$state"按- state对集合中的文档进行分区。- CA和- WA都有分区。
- sortBy: { orderDate: 1 }按- orderDate以升序 (- 1) 对每个分区中的文档进行排序,因此最早的- orderDate位于最前面。
- output:
- 该窗口包含在 - unbounded下限和使用时间范围单位将上限设置为- -10(当前文档的- orderDate值之前 10 个月)之间的文档。
- $push返回分区起始和满足如下条件的文档之间文档的- orderDate值的数组:- orderDate值在当前文档的- orderDate值(含)减去- 1010 个月范围内。
在此示例输出中,CA 和 WA 的 orderDate 值数组显示在 recentOrders 字段中:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),   "state" : "CA", "price" : 41, "quantity" : 162,   "recentOrders" : [ ] } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),   "state" : "CA", "price" : 13, "quantity" : 120,   "recentOrders" : [ ISODate("2019-05-18T16:09:01Z") ] } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),   "state" : "CA", "price" : 12, "quantity" : 145,   "recentOrders" : [ ISODate("2019-05-18T16:09:01Z") ] } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),   "state" : "WA", "price" : 43, "quantity" : 134,   "recentOrders" : [ ] } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),   "state" : "WA", "price" : 13, "quantity" : 104,   "recentOrders" : [ ISODate("2019-01-08T06:12:03Z") ] } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),   "state" : "WA", "price" : 14, "quantity" : 140,   "recentOrders" : [ ISODate("2019-01-08T06:12:03Z"), ISODate("2020-02-08T13:13:23Z") ] } 
与上一个值的比较示例
以下示例将 $setWindowFields 与 $shift 操作符和 $set 阶段结合使用来比较集合中的字段。
db.cakeSales.aggregate( [   {     $setWindowFields: {       partitionBy: "$type",       sortBy: { orderDate: 1 },       output: {         previousPrice: {           $shift: {             output: "$price",             by: -1           }         }       }     }   },   {     $set: {       priceComparison: {         $cond: [           { $eq: ["$price", "$previousPrice"] },           "same",           {             $cond: [               { $gt: ["$price", "$previousPrice"] },               "higher",               "lower"             ]           }         ]       }     }   }, ] ) 
在示例中:
- partitionBy: "$type"按- type对集合中的文档进行分区,以便每种类型的计算保持独立。
- sortBy: { orderDate: 1 }按- orderDate升序 (- 1) 对每个分区中的文档进行排序。
- output.previousPrice使用- $shift操作符从同一年内的前一个订单中捕获- price。
- $set添加一个名为- priceComparison的新字段,并根据与- previousPrice的比较将该字段的值设置为- higher、- lower或- same。
在此示例输出中,比较结果显示在 priceComparison字段中:
[   {     _id: 0,     type: 'chocolate',     orderDate: ISODate('2020-05-18T14:10:30.000Z'),     state: 'CA',     price: 13,     quantity: 120,     previousPrice: null,     priceComparison: 'higher'   },   {     _id: 1,     type: 'chocolate',     orderDate: ISODate('2021-03-20T11:30:05.000Z'),     state: 'WA',     price: 14,     quantity: 140,     previousPrice: 13,     priceComparison: 'higher'   },   {     _id: 5,     type: 'strawberry',     orderDate: ISODate('2019-01-08T06:12:03.000Z'),     state: 'WA',     price: 43,     quantity: 134,     previousPrice: null,     priceComparison: 'higher'   },   {     _id: 4,     type: 'strawberry',     orderDate: ISODate('2019-05-18T16:09:01.000Z'),     state: 'CA',     price: 41,     quantity: 162,     previousPrice: 43,     priceComparison: 'lower'   },   {     _id: 3,     type: 'vanilla',     orderDate: ISODate('2020-02-08T13:13:23.000Z'),     state: 'WA',     price: 13,     quantity: 104,     previousPrice: null,     priceComparison: 'higher'   },   {     _id: 2,     type: 'vanilla',     orderDate: ISODate('2021-01-11T06:31:15.000Z'),     state: 'CA',     price: 12,     quantity: 145,     previousPrice: 13,     priceComparison: 'lower'   } ] 
以下 WeatherMeasurement 类表示天气测量集合中的文档:
public class WeatherMeasurement {     public Guid Id { get; set; }          public string LocalityId { get; set; }          public DateTime MeasurementDateTime { get; set; }        public float Rainfall { get; set; }          public float Temperature { get; set; } } 
要使用MongoDB .NET/ C#驾驶员将 $setWindowFields 阶段添加到聚合管道,请对 PipelineDefinition对象调用 SetWindowFields() 方法。
以下示例创建了一个管道阶段,该阶段使用 Rainfall 和 Temperature 字段计算每个地区过去一个月的累计降雨量和移动平均温度:
var pipeline = new EmptyPipelineDefinition<WeatherMeasurement>()     .SetWindowFields(         partitionBy: w => w.LocalityId,         sortBy: Builders<WeatherMeasurement>.Sort.Ascending(             w => w.MeasurementDateTime),         output: o => new         {             MonthlyRainfall = o.Sum(                 w => w.Rainfall, RangeWindow.Create(                     RangeWindow.Months(-1),                     RangeWindow.Current)             ),             TemperatureAvg = o.Average(                 w => w.Temperature, RangeWindow.Create(                     RangeWindow.Months(-1),                     RangeWindow.Current)             )         }     ); 
本页中的 Node.js 示例使用来自 Atlas 示例数据集的 sample_weatherdata.data 集合。要学习如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅 MongoDB Node.js 驱动程序文档中的入门指南。
要使用MongoDB Node.js驾驶员将 $setWindowFields 阶段添加到聚合管道,请在管道对象中使用 $setWindowFields操作符。
以下示例创建了一个管道阶段,该阶段计算过去一个月内 callLetters 的每个唯一值的平均 airTemperature.value和总 waveMeasurement.waves.height 。然后,示例运行聚合管道:
const pipeline = [   {     $setWindowFields: {       partitionBy: "$callLetters",       sortBy: { ts: 1 },       output: {         temperatureAvg: {           $avg: "$airTemperature.value",           window: {             range: [-1, "current"],             unit: "month"           }         },         totalWaveHeight: {           $sum: "$waveMeasurement.waves.height",           window: {             range: [-1, "current"],             unit: "month"           }         }       }     }   }, ]; const cursor = collection.aggregate(pipeline); return cursor; 
提示
有关物联网功耗的其他示例,请参阅实用 MongoDB 聚合电子书。