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