All, although this question was marked as a duplicate, I'm still having issues, searching through the example, I'm still not able to figure out how to perform a sum / count of a nested array in mongodb please see below.
I'm using mongoose autopopulate to store the ids within the arrays and display them when performing a find.
I want to lookup the employee.discussions array and return the sum of occurrences on my Discussion collection. I'm able to get the count of discussions, but not the sum of discussions.occurrece.
My query:
//Show Single Route
router.get("/:id", isLoggedin, function(req, res){
var pipeline = [
{ "$match" : {"employeeuserid" : 'jbarmak' }},
{ "$unwind": "$discussions" },
{
"$group": {
"_id": null,
"eventwaiver": { "$sum": 1 }
}
}
];
Employee.aggregate(pipeline)
.exec(function(err, results){
if (err) throw err;
console.log(results);
});
Employee.findById(req.params.id, function (err, foundEmployee){
if(err){
res.redirect('/employee');
} else {
res.render('employees/show', {employee: foundEmployee});
}
});
});
Employee Collection
{
"_id": {
"$oid": "5ad7cf42729b4c08ae721603"
},
"author": {
"id": {
"$oid": "5ac2f25bbfb8ef001411fd01"
},
"username": "gmotta"
},
"qcerrors": [
{
"$oid": "5add3bc296d0a6265c04c674"
}
],
"employeesapnumber": 10001186,
"employeeuserid": "jbarmak",
"firstname": "jaouad",
"lastname": "barmaki",
"warehouseid": "1090",
"shift": 2,
"department": "Picking",
"position": "Contractor",
"hiredate": {
"$date": "2010-12-02T00:00:00.000Z"
},
"myimage": "myimage-1524092737893.PNG",
"__v": 50,
"discussions": [
{
"$oid": "5add0bf211e77d08106edc9b"
},
{
"$oid": "5add0c2311e77d08106edc9d"
},
{
"$oid": "5add136511e77d08106edca1"
},
{
"$oid": "5add148467850c0ca35ff74a"
},
{
"$oid": "5add14a967850c0ca35ff74c"
},
{
"$oid": "5add1eb9579cf80d86310f7d"
},
{
"$oid": "5adecf7e0264cc0e7aada389"
}
],
"safetyincidents": [
{
"$oid": "5adeb5260264cc0e7aada385"
}
]
}
How can I sum the occurrences in the nested array and console.log the result?
Dicussion collection:
{
"_id": {
"$oid": "5adfb054a590b10eef004b63"
},
"author": {
"id": {
"$oid": "5ac2f25bbfb8ef001411fd01"
},
"username": "gmotta"
},
"datetime": {
"$date": "2018-02-02T14:02:00.000Z"
},
"reasondiscussion": "None",
"reasontimeoff": "Bereavement",
"warning": "None",
"hours": 8,
"plannedunplanned": "Unplanned",
"occurrence": 1,
"description": "I'm calling in because I'm sick.",
"shift": 1,
"department": "Pallet-Pack",
"employeeid": "tkane",
"__v": 0
}