$avg (aggregation)

On this page本页内容

Definition定义

Changed in version 5.0.在版本5.0中更改

$avg

Returns the average value of the numeric values. 返回数值的平均值。$avg ignores non-numeric values.忽略非数值。

$avg is available in these stages:在以下阶段可用:

  • $addFields (Available starting in MongoDB 3.4)(从MongoDB 3.4开始提供)
  • $bucket
  • $bucketAuto
  • $group
  • $match stage that includes an $expr expression包含$expr表达式的阶段
  • $project
  • $replaceRoot (Available starting in MongoDB 3.4)(从MongoDB 3.4开始提供)
  • $replaceWith (Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)
  • $set (Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)
  • $setWindowFields (Available starting in MongoDB 5.0)(从MongoDB 5.0开始提供)

In MongoDB 3.2 and earlier, $avg is available in the $group stage only.在MongoDB 3.2及更早版本中,$avg仅在$group阶段可用。

Syntax语法

When used in the $bucket, $bucketAuto, $group, and $setWindowFields stages, $avg has this syntax:$bucket$bucketAuto$group$setWindowFields阶段中使用时,$avg具有以下语法:

{ $avg: <expression> }

When used in other supported stages, $avg has one of two syntaxes:当在其他支持的阶段中使用时,$avg有两种语法之一:

  • $avg has one specified expression as its operand:具有一个指定表达式作为其操作数:

    { $avg: <expression> }
  • $avg has a list of specified expressions as its operand:具有指定表达式列表作为其操作数:

    { $avg: [ <expression1>, <expression2> ... ]  }

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

Non-numeric or Missing Values非数值或缺失值

$avg ignores non-numeric values, including missing values. 忽略非数值,包括丢失的值。If all of the operands for the average are non-numeric, $avg returns null since the average of zero values is undefined.如果平均值的所有操作数都是非数字的,$avg返回null,因为零值的平均值未定义。

Array Operand数组操作数

In the $group stage, if the expression resolves to an array, $avg treats the operand as a non-numerical value.$group阶段,如果表达式解析为数组,$avg将操作数视为非数值。

In the other supported stages:在其他支持阶段:

  • With a single expression as its operand, if the expression resolves to an array, $avg traverses into the array to operate on the numerical elements of the array to return a single value.使用单个表达式作为其操作数,如果表达式解析为数组,$avg遍历数组以对数组中的数字元素进行操作以返回单个值。
  • With a list of expressions as its operand, if any of the expressions resolves to an array, $avg does not traverse into the array but instead treats the array as a non-numerical value.使用表达式列表作为其操作数,如果任何表达式解析为数组,$avg不会遍历数组,而是将数组视为非数值。

Examples示例

Use in $group Stage$group阶段中使用

Consider a sales collection with the following documents:考虑具有以下文档的sales集合:

{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:12:00Z") }

Grouping the documents by the item field, the following operation uses the $avg accumulator to compute the average amount and average quantity for each grouping.按照item字段对文档进行分组,以下操作使用$avg累加器计算每个分组的平均金额和平均数量。

db.sales.aggregate(
   [
     {
       $group:
         {
           _id: "$item",
           avgAmount: { $avg: { $multiply: [ "$price", "$quantity" ] } },
           avgQuantity: { $avg: "$quantity" }
         }
     }
   ]
)

The operation returns the following results:该操作返回以下结果:

{ "_id" : "xyz", "avgAmount" : 37.5, "avgQuantity" : 7.5 }
{ "_id" : "jkl", "avgAmount" : 20, "avgQuantity" : 1 }
{ "_id" : "abc", "avgAmount" : 60, "avgQuantity" : 6 }

Use in $project Stage$project阶段使用

A collection students contains the following documents:students集合包含以下文件:

{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }

The following example uses the $avg in the $project stage to calculate the average quiz scores, the average lab scores, and the average of the final and the midterm:以下示例使用$project阶段的$avg计算平均测验分数、平均实验室分数以及期末和期中考试的平均值:

db.students.aggregate([
   { $project: { quizAvg: { $avg: "$quizzes"}, labAvg: { $avg: "$labs" }, examAvg: { $avg: [ "$final", "$midterm" ] } } }
])

The operation results in the following documents:该操作产生以下文件:

{ "_id" : 1, "quizAvg" : 7.666666666666667, "labAvg" : 6.5, "examAvg" : 77.5 }
{ "_id" : 2, "quizAvg" : 9.5, "labAvg" : 8, "examAvg" : 87.5 }
{ "_id" : 3, "quizAvg" : 4.666666666666667, "labAvg" : 5.5, "examAvg" : 74 }

Use in $setWindowFields Stage$setWindowFields阶段中使用

New in version 5.0.在版本5.0中新增

Create a cakeSales collection that contains cake sales in the states of California (CA) and Washington (WA):创建包含加利福尼亚州(CA)和华盛顿州(WA)蛋糕销售的cakeSales系列:

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 }
] )

This example uses $avg in the $setWindowFields stage to output the moving average for the cake sales quantity for each state:本示例使用$setWindowFields阶段中的$avg输出每个state的蛋糕销售quantity的移动平均值:

db.cakeSales.aggregate( [
   {
      $setWindowFields: {
         partitionBy: "$state",
         sortBy: { orderDate: 1 },
         output: {
            averageQuantityForState: {
               $avg: "$quantity",
               window: {
                  documents: [ "unbounded", "current" ]
               }
            }
         }
      }
   }
] )

In the example:在该示例中:

  • partitionBy: "$state" partitions the documents in the collection by state. state对集合中的文档进行分区There are partitions for CA and WA.有用于CAWA的分区。
  • sortBy: { orderDate: 1 } sorts the documents in each partition by orderDate in ascending order (1), so the earliest orderDate is first.orderDate按升序(1)对每个分区中的文档进行排序,因此最早的OrderDate是第一个。
  • output sets the averageQuantityForState field to the moving average quantity using $avg for the documents in a documents window.output使用$avg文档窗口中的文档将averageQuantityForState字段设置为移动平均quantity

    The window contains documents between an unbounded lower limit and the current document in the output. 窗口包含的文档位于unbounded下限和输出中的current文档之间。This means $avg returns the moving average quantity for the documents between the beginning of the partition and the current document.这意味着$avg返回分区开始和当前文档之间文档的移动平均quantity

In this output, the moving average quantity for CA and WA is shown in the averageQuantityForState field:在该输出中,CAWA的移动平均quantity显示在averageQuantityForState字段中:

{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),
  "state" : "CA", "price" : 41, "quantity" : 162, "averageQuantityForState" : 162 }
{ "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),
  "state" : "CA", "price" : 13, "quantity" : 120, "averageQuantityForState" : 141 }
{ "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),
  "state" : "CA", "price" : 12, "quantity" : 145, "averageQuantityForState" : 142.33333333333334 }
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),
  "state" : "WA", "price" : 43, "quantity" : 134, "averageQuantityForState" : 134 }
{ "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),
  "state" : "WA", "price" : 13, "quantity" : 104, "averageQuantityForState" : 119 }
{ "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),
  "state" : "WA", "price" : 14, "quantity" : 140, "averageQuantityForState" : 126 }
←  $atanh (aggregation)$binarySize (aggregation) →