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
Sum the score of duplicate column values in MongoDB documents?
To sum values of duplicate column entries in MongoDB, use the $group stage with $sum aggregation operator. This groups documents by a field and calculates the total of specified numeric fields.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$groupingField",
field1Sum: { $sum: "$field1" },
field2Sum: { $sum: "$field2" }
}
}
]);
Sample Data
db.demo512.insertMany([
{"Name": "Chris", "Score1": 45, "Score2": 65, "CountryName": "US"},
{"Name": "Chris", "Score1": 41, "Score2": 45, "CountryName": "US"},
{"Name": "Bob", "Score1": 75, "Score2": 55, "CountryName": "US"},
{"Name": "Bob", "Score1": 65, "Score2": 90, "CountryName": "US"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e884d96987b6e0e9d18f588"),
ObjectId("5e884da2987b6e0e9d18f589"),
ObjectId("5e884db2987b6e0e9d18f58a"),
ObjectId("5e884dc2987b6e0e9d18f58b")
]
}
Display Sample Data
db.demo512.find();
{ "_id": ObjectId("5e884d96987b6e0e9d18f588"), "Name": "Chris", "Score1": 45, "Score2": 65, "CountryName": "US" }
{ "_id": ObjectId("5e884da2987b6e0e9d18f589"), "Name": "Chris", "Score1": 41, "Score2": 45, "CountryName": "US" }
{ "_id": ObjectId("5e884db2987b6e0e9d18f58a"), "Name": "Bob", "Score1": 75, "Score2": 55, "CountryName": "US" }
{ "_id": ObjectId("5e884dc2987b6e0e9d18f58b"), "Name": "Bob", "Score1": 65, "Score2": 90, "CountryName": "US" }
Example: Sum Scores by Name
Group documents by Name and sum the Score1 and Score2 values ?
db.demo512.aggregate([
{
"$group": {
"_id": "$Name",
"Score1": { "$sum": "$Score1" },
"Score2": { "$sum": "$Score2" },
"CountryName": { "$first": "$CountryName" }
}
},
{
"$project": {
"_id": 0,
"Name": "$_id",
"Score1": 1,
"Score2": 1,
"CountryName": 1
}
}
]);
{ "Score1": 140, "Score2": 145, "CountryName": "US", "Name": "Bob" }
{ "Score1": 86, "Score2": 110, "CountryName": "US", "Name": "Chris" }
How It Works
-
$groupgroups documents by theNamefield -
$sumcalculates the total of Score1 and Score2 for each group -
$firstpicks the first CountryName value from each group -
$projectreshapes the output to show Name instead of _id
Conclusion
Use $group with $sum to aggregate numeric values for duplicate entries. The result shows Chris's total scores (86, 110) and Bob's total scores (140, 145) from their respective duplicate documents.
Advertisements
