mongoose - MongoDB Aggregation Multiple Keys -


i trying aggregate employees using department , status calculate summ each status. 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 try via:

employee.aggregate(           { $group: {             _id: '$department',             statuses: { $addtoset: "$status" }         }},         { $project: { _id: 1, statuses: 1 }},         function(err, summary) {             console.log(summary);         }     ); 

i statuses in array, produced "$addtoset":

{   department: "hr",   statuses: [       'exist',       'absent'   ] }, {   department: "acme",   statuses: [       'exist',       'absent'   ] } ... 

how right put "{$sum: 1}" each of statuses? thank you'r response.

if possible status exist , absent, use $cond operator in conjunction $eq operator.

{      $group : {         _id : '$department',         exist :  { $sum : {  $cond : [ { $eq : ['$status', 'exist'] }  ,1,0 ]  } },         absent :  { $sum : {  $cond : [ { $eq : ['$status', 'absent'] }  ,1,0 ]  } }     }  } 

after grouping, project want


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -