On this page本页内容
$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
$set
$replaceRoot
$replaceWith
$match
stage that includes an $expr
expression$match
阶段,包含一个$expr
表达式In MongoDB 3.2 and earlier, 在MongoDB 3.2及更早版本中,$avg
is available in the $group
stage only.$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
具有以下语法,并返回将指定表达式应用于共享同一组密钥的文档中的每个文档所产生的所有数值的集合平均值:
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
$avg
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
$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
,因为未定义零值的平均值。
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:在其他受支持的阶段:
$avg
traverses into the array to operate on the numerical elements of the array to return a single value.$avg
遍历数组,对数组的数字元素进行操作,以返回单个值。$avg
does not traverse into the array but instead treats the array as a non-numerical value.$avg
不会遍历数组,而是将数组视为非数值。$group
Stage$group
阶段使用¶Consider a 考虑一个sales
collection with the following documents:sales
集合带有以下文档:
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
累加器来计算每个分组的平均金额和平均数量。
The operation returns the following results:操作返回以下结果:
$project
Stage$project
阶段使用¶A collection students
contains the following documents:students
集合包括以下文件:
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
计算平均测验分数、平均实验室分数以及期末和期中考试的平均分数:
The operation results in the following documents:该操作将生成以下文档:
In the other supported stages:在其他受支持的阶段:
$avg
traverses into the array to operate on the numerical elements of the array to return a single value.$avg
遍历数组,对数组的数字元素进行操作,以返回单个值。$avg
does not traverse into the array but instead treats the array as a non-numerical value.$avg
不会遍历数组,而是将数组视为非数值。