$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.

CategoryAccumulators
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏