对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$avg(窗口函数)

$avg

返回来自特定窗口的平均值。

注意

消歧

本页介绍 $avg 在用作 窗口函数 时的情况。

您还可以在这些其他上下文中使用 $avg:

{ $setWindowFields: { ... output: { <field>: { $avg: <expression> } } }}

默认返回类型是 double。如果至少有一个输入值是 decimal,则返回类型为 decimal。

$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 窗口函数输出蛋糕销售 quantity 的每个 state 的移动平均值。对于每个省/市/自治区,向每个文档添加一个字段,该字段包含订单和所有上一个订单的平均数量。

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 位于最前面。

  • output 在文档窗口中,将文档的 averageQuantityForState 字段设置为移动平均值 quantity。

    该窗口包含介于 unbounded 下限与输出中 current 文档之间的文档。这意味着 $avg 会返回分区开始和当前文档之间文档的 quantity 移动平均值(包括在内)。

给本页内容打分