MongoDB: average value of field
To calculate the average value of a field in MongoDB using the shell, the aggregation framework with the
$avg operator is utilized.Example 1: Calculating the average of a field across the entire collection
Assume a collection named
products with documents like:{ "_id": 1, "item": "A", "price": 10 }
{ "_id": 2, "item": "B", "price": 15 }
{ "_id": 3, "item": "C", "price": 20 }
{ "_id": 4, "item": "D", "price": 12 }
To find the average
price of all products:db.products.aggregate([
{
$group: {
_id: null, // Group all documents into a single group
averagePrice: { $avg: "$price" } // Calculate the average of the 'price' field
}
}
])
This query would return a result similar to:
{ "_id": null, "averagePrice": 14.25 }
Example 2: Calculating the average of a field grouped by another field
To find the average
price grouped by item:db.products.aggregate([
{
$group: {
_id: "$item", // Group documents by the 'item' field
averagePrice: { $avg: "$price" } // Calculate the average of 'price' for each group
}
}
])
If the
products collection contains:{ "_id": 1, "item": "A", "price": 10 }
{ "_id": 2, "item": "B", "price": 15 }
{ "_id": 3, "item": "A", "price": 20 }
{ "_id": 4, "item": "B", "price": 12 }
This query would return a result similar to:
[
{ "_id": "B", "averagePrice": 13.5 },
{ "_id": "A", "averagePrice": 15 }
]