全部,虽然这个问题被标记为重复,但我仍然遇到问题,通过示例搜索,我仍然无法弄清楚如何执行嵌套数组的总和/计数在mongodb,请看下面。
我使用mongoose autopopulate将数据存储在数组中,并在执行查找时显示它们。
我想查找employee.discussions数组并返回我的Discussion集合中出现的总和。我能够得到讨论的数量,但不能讨论讨论的总和。电影。
我的查询:
//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});
}
});
});
员工收集
{
"_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"
}
]
}
如何在嵌套数组和console.log中对结果进行求和?
Dicussion系列:
{
"_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
}