I trying to aggregate employees using department and status to calculate summ for each status. From this:
{
name : "Employee_1",
department: "hr",
status : "exist"
},
{
name : "Employee_2",
department: "acme",
status : "absent"
},
{
name : "Employee_3",
department: "acme",
status : "absent"
}
...
to this:
{
department: "hr",
statuses: {
exist: 1,
absent: 0
}
},
{
department: "acme",
statuses: {
exist: 0,
absent: 2
}
}
...
I was try to do it via:
Employee.aggregate(
{ $group: {
_id: '$department',
statuses: { $addToSet: "$status" }
}},
{ $project: { _id: 1, statuses: 1 }},
function(err, summary) {
console.log(summary);
}
);
I get only statuses in array, produced by "$addToSet":
{
department: "hr",
statuses: [
'exist',
'absent'
]
},
{
department: "acme",
statuses: [
'exist',
'absent'
]
}
...
How to right put "{$sum: 1}" for each of statuses? Thank for you'r response.