Introduction
The $avg accumulator helps you find the average value of numbers in a group. It makes it easy to calculate the mean without doing math yourself.
The $avg accumulator helps you find the average value of numbers in a group. It makes it easy to calculate the mean without doing math yourself.
{ $avg: <expression> }The <expression> is usually a field name that holds numbers.
You use $avg inside aggregation stages like $group.
score field values.{ $avg: "$score" }price field and the number 10.{ $avg: [ "$price", 10 ] }This query groups students by their class and calculates the average score for each class.
db.students.aggregate([
{
$group: {
_id: "$class",
averageScore: { $avg: "$score" }
}
}
])If the field has no numeric values, $avg returns null.
You can use $avg with arrays by passing an array of expressions.
$avg calculates the average of numeric values in a group.
It is used inside aggregation pipelines, mostly with $group.
It helps quickly find mean values without manual calculations.
$avg accumulator do in a MongoDB aggregation pipeline?$avg$avg accumulator is designed to calculate the mean (average) of numeric values within grouped documents in an aggregation pipeline.$sum, $max, and $count perform different tasks, so $avg specifically calculates averages.$avg = average calculation [OK]score in a MongoDB aggregation $group stage?$avg, not $average or avg.$avg, and the whole inside a $group stage with an _id.students with documents:{ "name": "Alice", "score": 80 }, { "name": "Bob", "score": 90 }, { "name": "Charlie", "score": 70 }[{ $group: { _id: null, averageScore: { $avg: "$score" } } }][{ $group: { _id: "$class", avgScore: { $avg: score } } }]sales with documents:{ "region": "North", "amount": 100 }, { "region": "South", "amount": 200 }, { "region": "North", "amount": 300 }, { "region": "South", "amount": 400 }$group with _id: "$region" and $avg: "$amount" to get average sales per region.avgAmount descending (-1) to get highest average first, then limit to 1 document.Pass the test and this pattern moves unknown