我尝试使用部门和状态汇总员工以计算每个状态的总和。由此:
{
name : "Employee_1",
department: "hr",
status : "exist"
},
{
name : "Employee_2",
department: "acme",
status : "absent"
},
{
name : "Employee_3",
department: "acme",
status : "absent"
}
...
对此:
{
department: "hr",
statuses: {
exist: 1,
absent: 0
}
},
{
department: "acme",
statuses: {
exist: 0,
absent: 2
}
}
...
我试图通过以下方式做到这一点:
Employee.aggregate(
{ $group: {
_id: '$department',
statuses: { $addToSet: "$status" }
}},
{ $project: { _id: 1, statuses: 1 }},
function(err, summary) {
console.log(summary);
}
);
我只得到数组中的状态,由“$addToSet”产生:
{
department: "hr",
statuses: [
'exist',
'absent'
]
},
{
department: "acme",
statuses: [
'exist',
'absent'
]
}
...
如何为每个状态正确放置“{$sum: 1}”?谢谢你的回复。