4.8 C
London
Saturday, December 28, 2024
HomeMongoDBAggregation in MongoDBMongoDB: How to Calculate the Sum of a Field

MongoDB: How to Calculate the Sum 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 sum of values in a field in MongoDB:

Method 1: Calculate Sum of Field

db.collection.aggregate([{$group: {_id:null, sum_val:{$sum:"$valueField"}}}])

Method 2: Calculate Sum of Field by Group

db.collection.aggregate([{$group: {_id:"$groupField", sum_val:{$sum:"$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 Sum of Field

We can use the following code to calculate the sum of values in the points field:

db.teams.aggregate([{$group: {_id:null, sum_val:{$sum:"$points"}}}])

This query returns the following results:

{ _id: null, sum_val: 130} 

From the results we can see that the sum of values in the points field is 130.

We can manually verify this is correct by calculating the sum of the points values by hand:

Sum of Points: 30 + 30 + 20 + 25 + 25 = 130.

Example 2: Calculate Sum of Field by Group

We can use the following code to calculate the sum of the values in the points field, grouped by the team field:

db.teams.aggregate([{$group: {_id:"$team", sum_val:{$sum:"$points"}}}])

This query returns the following results:

{ _id: 'Spurs', sum_val: 60 }
{ _id: 'Mavs', sum_val: 70 } 

From the results we can see:

  • The sum of points for the Spurs is 60.
  • The sum of points for the Mavs is 70.

Note: You can find the complete documentation for the $sum function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

How to Calculate the Median Value in MongoDB
How to Calculate the Average Value in MongoDB
How to Calculate the Max Value in MongoDB

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