定义
返回特定窗口值的平均值。
注意
消歧
本页介绍了用作窗口函数的 $avg。
您还可以在其他上下文中使用 $avg:
$avg (accumulator),它会根据可变数量的输入文档返回单个聚合值。$avg (expression),返回大量中数值元素的平均值。
语法
{ $setWindowFields: { ... output: { <field>: { $avg: <expression> } } } }
行为
结果类型
默认返回类型为双精度值。如果至少一个输入值为十进制,则返回类型为十进制。
非数值或缺失值
$avg 忽略非数字值,包括缺失值。如果所有输入值都是非数字值,则 $avg 返回 null。
例子
创建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 } ] )
此示例使用 $avg窗口函数输出每个 state 的蛋糕销售 quantity 的移动平均值。对于每个州,在每个文档中添加一个字段,其中包含订单和所有先前订单的平均数量。
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { averageQuantityForState: { $avg: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
CA 和 WA 的移动平均值 quantity 显示在 averageQuantityForState字段中:
[ { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, averageQuantityForState: 162 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, averageQuantityForState: 141 }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, averageQuantityForState: 142.33333333333334 }, { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, averageQuantityForState: 134 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, averageQuantityForState: 119 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, averageQuantityForState: 126 } ]
在前面的示例中:
partitionBy: "$state"按state对集合中的文档分区。CA和WA都有分区。sortBy: { orderDate: 1 }按orderDate以升序 (1) 对每个分区中的文档进行排序,因此最早的orderDate位于最前面。