- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Group Accumulator Operators >
- $avg (aggregation)
$avg (aggregation)¶
On this page
Definition¶
-
$avg¶ Returns the average value of the numeric values.
$avgignores non-numeric values.Changed in version 3.2:
$avgis available in the$groupand$projectstages. In previous versions of MongoDB,$avgis available in the$groupstage only.When used in the
$groupstage,$avghas 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
$projectstage,$avgreturns the average of the specified expression or list of expressions for each document and has one of two syntaxes:$avghas one specified expression as its operand:$avghas 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,
$avgtraverses 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,
$avgdoes 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,
$avgtraverses 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,
$avgdoes not traverse into the array but instead treats the array as a non-numerical value.