$avg (aggregation)
Definition
$avg
- Returns the average value of the numeric values.
$avg
ignores non-numeric values.
$avg
is available in the following stages:
$group
$project
$addFields
(Available starting in MongoDB 3.4)$set
(Available starting in MongoDB 4.2)$replaceRoot
(Available starting in MongoDB 3.4)$replaceWith
(Available starting in MongoDB 4.2)$match
stage that includes an$expr
expressionIn MongoDB 3.2 and earlier,$avg
is available in the$group
stage only.
When used in the $group
stage, $avg
has thefollowing syntax and returns the collective average of all the numericvalues that result from applying a specified expression to eachdocument in a group of documents that share the same group by key:
- { $avg: <expression> }
When used in the other supported stages, $avg
returnsthe average of the specified expression or list of expressions foreach document and has one of two syntaxes:
$avg
has one specified expression as its operand:
- { $avg: <expression> }
$avg
has a list of specified expressions as itsoperand:
- { $avg: [ <expression1>, <expression2> ... ] }
For more information on expressions, seeExpressions.
Behavior
Non-numeric or Missing Values
$avg
ignores non-numeric values, including missing values. If all of theoperands for the average are non-numeric, $avg
returnsnull
since the average of zero values is undefined.
Array Operand
In the $group
stage, if the expression resolves to anarray, $avg
treats the operand as a non-numerical value.
In the other supported stages:
- With a single expression as its operand, if the expression resolvesto an array,
$avg
traverses into the array to operate on thenumerical elements of the array to return a single value. - With a list of expressions as its operand, if any of the expressionsresolves to an array,
$avg
does not traverse into thearray but instead treats the array as a non-numerical value.
Examples
Use in $group Stage
Consider a sales
collection with the following documents:
- { "_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 operationuses the $avg
accumulator to compute the average amount andaverage quantity for each grouping.
- 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
A collection students
contains the following documents:
- { "_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, theaverage lab scores, and the average of the final and the midterm:
- 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 resolvesto an array,
$avg
traverses into the array to operate on thenumerical elements of the array to return a single value. - With a list of expressions as its operand, if any of the expressionsresolves to an array,
$avg
does not traverse into thearray but instead treats the array as a non-numerical value.