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
MongoDB Aggregate sum of values in a list of dictionaries for all documents?
To aggregate sum of values in a list of dictionaries for all documents, use $unwind to flatten the array, then $group with $sum operators to calculate totals by grouping field.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{
$group: {
_id: "$arrayField.groupByField",
"fieldSum1": { $sum: "$arrayField.field1" },
"fieldSum2": { $sum: "$arrayField.field2" }
}
}
]);
Sample Data
db.demo117.insertMany([
{
ID: 101,
Details: [
{
Name: "Chris",
Value1: 20,
Value2: 30,
Value3: 10
},
{
Name: "David",
Value1: 10,
Value2: 50,
Value3: 30
}
]
},
{
ID: 102,
Details: [
{
Name: "Chris",
Value1: 20,
Value2: 10,
Value3: 20
},
{
Name: "David",
Value1: 30,
Value2: 40,
Value3: 10
}
]
}
]);
Example
Aggregate sum of values by Name across all documents ?
db.demo117.aggregate([
{
$unwind: "$Details"
},
{
$group: {
_id: "$Details.Name",
"Value1": { $sum: "$Details.Value1" },
"Value2": { $sum: "$Details.Value2" },
"Value3": { $sum: "$Details.Value3" }
}
}
]);
{ "_id": "David", "Value1": 40, "Value2": 90, "Value3": 40 }
{ "_id": "Chris", "Value1": 40, "Value2": 40, "Value3": 30 }
How It Works
-
$unwindcreates a separate document for each element in the Details array -
$groupgroups documents by Name and sums the corresponding values -
$sumcalculates the total for each numeric field across all matching documents
Conclusion
Use $unwind followed by $group with $sum to aggregate values from nested arrays. This approach effectively flattens array data and calculates totals by grouping criteria.
Advertisements
