Home » MongoDB: How to Calculate the Sum of a Field

MongoDB: How to Calculate the Sum of a Field

by Tutor Aspire

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

You may also like