Reputation: 6512
I want to perform sum of employee points from mongodb documents.
My Documents in Employee Points Collections are like below
[
{
"EmployeeID": "Cust0001",
"Point": 1,
},
{
"EmployeeID": "Cust0002",
"Point": 2,
},
{
"EmployeeID": "Cust0003",
"Point": 1,
},
{
"EmployeeID": "Cust0001",
"Point": 5,
},
{
"EmployeeID": "Cust0001",
"Point": 2,
}
]
Expected result
[
{
"EmployeeID": "Cust0001",
"Total_Points": 8
},
{
"EmployeeID": "Cust0002",
"Total_Points": 2
},
{
"EmployeeID": "Cust0003",
"Total_Points": 1
}
]
Which is the best and most optimized way to get the output from mongodb with the total points.
I am using mongoose mongodb connection in my project.
I can manipulate data using a for loop but it seems rather inefficent.
Thanks in advance.
Comments are appreciated.
Upvotes: 3
Views: 1176
Reputation: 46491
You need to use $sum
twice here... One as "accumulator" for $group
stage and one for summation of Points
db.collection.aggregate([
{ "$group": {
"_id": "$EmployeeID",
"Point": {
"$sum": {
"$sum": "$Point"
}
}
}},
{ "$project": {
"EmployeeID": "$_id",
"Point": "$Point",
"_id": 0
}}
])
Ouput
[
{
"EmployeeID": "Cust0003",
"Point": 1
},
{
"EmployeeID": "Cust0002",
"Point": 2
},
{
"EmployeeID": "Cust0001",
"Point": 8
}
]
Check it here
Upvotes: 3