1.8 C
London
Friday, March 14, 2025
HomeMongoDBAggregation in MongoDBMongoDB: How to Calculate the Average Value of a Field

MongoDB: How to Calculate the Average Value of a Field

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories