Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to calculate sum in MongoDB with aggregate()?
To calculate sum in MongoDB, use the $sum operator along with the aggregate() method. The $sum operator is used within a $group stage to calculate the total of numeric field values across documents.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
totalFieldName: { $sum: "$fieldName" }
}
}
]);
Create Sample Data
Let us create a collection with documents having Amount field ?
db.demo337.insertMany([
{"Amount": 100},
{"Amount": 500},
{"Amount": 400}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5231e5f8647eb59e56209b"),
ObjectId("5e5231e9f8647eb59e56209c"),
ObjectId("5e5231ebf8647eb59e56209d")
]
}
Display Sample Data
db.demo337.find();
{ "_id": ObjectId("5e5231e5f8647eb59e56209b"), "Amount": 100 }
{ "_id": ObjectId("5e5231e9f8647eb59e56209c"), "Amount": 500 }
{ "_id": ObjectId("5e5231ebf8647eb59e56209d"), "Amount": 400 }
Example: Calculate Sum of Amount Field
Following is the query to calculate sum using aggregate() ?
db.demo337.aggregate([
{
$group: {
_id: null,
totalAmount: { $sum: "$Amount" }
}
}
]);
{ "_id": null, "totalAmount": 1000 }
How It Works
- The
$groupstage groups all documents together using_id: null -
$sum: "$Amount"adds up all Amount field values from the grouped documents - The result shows the calculated total in the totalAmount field
Conclusion
Use $sum within $group stage of aggregate() to calculate sum of numeric fields. Set _id: null to group all documents together for a total sum calculation.
Advertisements
