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
Find sum of fields inside array in MongoDB?
To find sum of fields inside array in MongoDB, use the $sum operator with the aggregation pipeline. The $sum operator can directly reference array fields using dot notation to calculate the total of numeric values.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": 1,
"totalSum": {
$sum: "$arrayName.fieldToSum"
}
}
}
]);
Sample Data
Let us create a collection with documents ?
db.demo96.insertOne({
"Name": "Chris",
"Details": [
{ "Marks": 67 },
{ "Marks": 33 },
{ "Marks": 50 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2d6aadb8903cdd865577ad")
}
Display Documents
db.demo96.find();
{
"_id": ObjectId("5e2d6aadb8903cdd865577ad"),
"Name": "Chris",
"Details": [
{ "Marks": 67 },
{ "Marks": 33 },
{ "Marks": 50 }
]
}
Example: Calculate Total Marks
Following is the query to find sum of fields inside array ?
db.demo96.aggregate([
{
$project: {
"Name": 1,
"TotalMarks": {
$sum: "$Details.Marks"
}
}
}
]);
{
"_id": ObjectId("5e2d6aadb8903cdd865577ad"),
"Name": "Chris",
"TotalMarks": 150
}
How It Works
The $sum operator with "$Details.Marks" automatically iterates through the Details array and sums all Marks values (67 + 33 + 50 = 150).
Conclusion
Use $sum with dot notation in the aggregation pipeline to calculate totals of numeric fields within arrays. The operator automatically processes all array elements and returns the cumulative sum.
Advertisements
