Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to calculate average
To calculate the average of numeric values in MongoDB, use the $avg aggregation operator within the $group stage. This operator computes the average of all specified numeric values across documents.
Syntax
db.collection.aggregate([
{
$group: {
"_id": null,
"averageField": { $avg: "$fieldName" }
}
}
]);
Sample Data
Let us create a collection with product price documents ?
db.demo80.insertMany([
{"Details": {"Price": 10.5}},
{"Details": {"Price": 50.3}},
{"Details": {"Price": 100.10}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2bf43271bf0181ecc42297"),
ObjectId("5e2bf43871bf0181ecc42298"),
ObjectId("5e2bf43f71bf0181ecc42299")
]
}
Verify Sample Data
db.demo80.find();
{ "_id": ObjectId("5e2bf43271bf0181ecc42297"), "Details": { "Price": 10.5 } }
{ "_id": ObjectId("5e2bf43871bf0181ecc42298"), "Details": { "Price": 50.3 } }
{ "_id": ObjectId("5e2bf43f71bf0181ecc42299"), "Details": { "Price": 100.1 } }
Calculate Average Price
Use the $avg operator to calculate the average of all prices ?
db.demo80.aggregate([
{
$group: {
"_id": null,
"AvgValue": {
"$avg": "$Details.Price"
}
}
}
]);
{ "_id": null, "AvgValue": 53.633333333333326 }
Key Points
- The
$avgoperator ignores non-numeric values and null values in calculations. - Setting
"_id": nullgroups all documents together for a single average result. - Use dot notation like
"$Details.Price"to access nested field values.
Conclusion
The $avg aggregation operator efficiently calculates averages of numeric fields across documents. Use it within $group stages to compute statistical summaries of your data collections.
Advertisements
