我想从mongodb文档执行员工积分的总和.
我的员工积分集中的文档如下所示
[
{
"EmployeeID": "Cust0001",
"Point": 1,
},
{
"EmployeeID": "Cust0002",
"Point": 2,
},
{
"EmployeeID": "Cust0003",
"Point": 1,
},
{
"EmployeeID": "Cust0001",
"Point": 5,
},
{
"EmployeeID": "Cust0001",
"Point": 2,
}
]
预期结果
[
{
"EmployeeID": "Cust0001",
"Total_Points": 8
},
{
"EmployeeID": "Cust0002",
"Total_Points": 2
},
{
"EmployeeID": "Cust0003",
"Total_Points": 1
}
]
这是从mongodb获得总点数的最佳,最优化的方法.
我在项目中使用mongoose mongodb连接.
我可以使用for循环来操作数据,但效率似乎很低.
提前致谢.
评论被赞赏.
解决方法:
您需要在这里两次使用$sum
…一种作为$group
阶段的“累加器”,另一种作为积分的总和
db.collection.aggregate([
{ "$group": {
"_id": "$EmployeeID",
"Point": {
"$sum": {
"$sum": "$Point"
}
}
}},
{ "$project": {
"EmployeeID": "$_id",
"Point": "$Point",
"_id": 0
}}
])
乌普特
[
{
"EmployeeID": "Cust0003",
"Point": 1
},
{
"EmployeeID": "Cust0002",
"Point": 2
},
{
"EmployeeID": "Cust0001",
"Point": 8
}
]
检查它here