$avg (aggregation)
On this page
Definition
-
$avg
-
Returns the average value of the numeric values.
$avg
ignores non-numeric values.Changed in version 3.2:
$avg
is available in the$group
and$project
stages. In previous versions of MongoDB,$avg
is available in the$group
stage only.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:When used in the
$project
stage,$avg
returns the average of the specified expression or list of expressions for each document and has one of two syntaxes:$avg
has one specified expression as its operand:$avg
has a list of specified expressions as its operand:
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.
Array Operand
In the $group
stage, if the expression resolves to an array, $avg
treats the operand as a non-numerical value.
In the $project
stage:
- 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. - 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.
Examples
Use in $group
Stage
Consider a sales
collection with the following documents:
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.
The operation returns the following results:
Use in $project
Stage
A collection students
contains the following documents:
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:
The operation results in the following documents:
In the $project
stage:
- 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. - 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.