$avg (aggregation)

On this page本页内容

Definition定义

$avg

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

$avg is available in the following stages:在以下阶段中可用:

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

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

When used in the $group stage, $avg has the following syntax and returns the collective average of all the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key:$group阶段中使用时,$avg具有以下语法,并返回将指定表达式应用于共享同一组密钥的文档中的每个文档所产生的所有数值的集合平均值:

{ $avg: <expression> }

When used in the other supported stages, $avg returns the average of the specified expression or list of expressions for each document and 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. $avg忽略非数值,包括缺少的值。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 }

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不会遍历数组,而是将数组视为非数值。