You can use the following methods to calculate the average value of a field in MongoDB:
Method 1: Calculate Average of Field
db.collection.aggregate([{$group: {_id:null, avg_val:{$avg:"$valueField"}}}])
Method 2: Calculate Average of Field by Group
db.collection.aggregate([{$group: {_id:"$groupField", avg_val:{$avg:"$valueField"}}}])
The following examples show how to use each method with a collection teams with the following documents:
db.teams.insertOne({team: "Mavs", points: 30, rebounds: 8}) db.teams.insertOne({team: "Mavs", points: 30, rebounds: 12}) db.teams.insertOne({team: "Spurs", points: 20, rebounds: 7}) db.teams.insertOne({team: "Spurs", points: 25, rebounds: 5}) db.teams.insertOne({team: "Spurs", points: 25, rebounds: 9})
Example 1: Calculate Average of Field
We can use the following code to calculate the average value of the points field:
db.teams.aggregate([{$group: {_id:null, avg_val:{$avg:"$points"}}}])
This query returns the following results:
{ _id: null, avg_val: 26 }
From the results we can see that the average value in the points field is 26.
We can manually verify this is correct by calculating the average of the points values by hand:
Average of Points: (30 + 30 + 20 + 25 + 25) / 5 = 26.
Example 2: Calculate Average of Field by Group
We can use the following code to calculate the average value of the points field, grouped by the team field:
db.teams.aggregate([{$group: {_id:"$team", avg_val:{$avg:"$points"}}}])
This query returns the following results:
{ _id: 'Spurs', avg_val: 23.333333333333332 } { _id: 'Mavs', avg_val: 30 }
From the results we can see:
- The average points value for the Spurs is 23.33.
- The average points value for the Mavs is 30.
Note: You can find the complete documentation for the $avg function here.
Additional Resources
The following tutorials explain how to perform other common operations in MongoDB:
MongoDB: How to Add a New Field
MongoDB: How to Remove a Field
MongoDB: How to Group By and Count
MongoDB: How to Group By Multiple Fields