对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

$avg(窗口函数)

$avg

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

注意

消歧

本页介绍了用作窗口函数的 $avg。

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

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

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

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

给本页内容打分