$avg (Average Accumulator)
Last updated: 2026-10-09
$avg (Average Accumulator)
$avg is an accumulator computing the average of a field across a group in $group, or the average of array elements in $project. It ignores null and missing values, averaging only numbers. Common in reporting; the averaged expression may be arbitrarily complex.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, avg: { $avg: "$field" } } } // or average an array in $project
Returns:Numeric average (null and missing values ignored)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $avg: average price per item
db.sales.aggregate([
{ $group: { _id: '$item', avg: { $avg: '$price' } } }
])
Output:
{ "_id": "Pen", "avg": 45.5 }
{ "_id": "Book", "avg": 12.0 }
📌 Notes
- Null, missing, and non-numeric values are ignored
- In $project it averages array elements
- Combine with $sum and $count for weighted averages
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
$facet + $bucket + Text/Geospatial Search
📚 Related Tutorials
❓ FAQ
QWhat happens when $avg hits a missing field?
AMissing and null values are ignored; only present numbers are averaged.
QCan $avg be used in $project?
AYes, it averages array elements, e.g. { $project: { a: { $avg: '$scores' } } }.
QHow do I compute a weighted average?
AAccumulate value-times-weight with $sum and divide by the $sum of weights.