怎么办聚集和组MongoDB中的一个子领域是一个数组?
我建立一个API,用于签入和签员工出去考勤系统。公司为每位员工我需要总结一年的工作一个月,然后总小时数。我试着用聚集,项目组,但我没有收到在一个月或一年的总工时员工。
我的方案的一部分是这样的:
const EmployeeSchema = new Schema({
_id: Schema.Types.ObjectId,
attendance: [{
date: {type: Date, default: Date.now},
entry: {type: Date, required: false},
exit: {
time: {type: Date, required: false}
},
totalHours: {type: Number, required: false}
}]
)}
对于聚集,我试图实现这种方式:
exports.aggregation = (req, res) => {
const id = req.params.salespersonId;
DailySalesPerson.aggregate([
{$unwind: "$attendance"},
{
$group: {
_id: {
month: {"$month":"$attendance.date"}
},
totalHours: {$sum: "totalHours"},
count: {$sum: 1}
}
},
])
.then(result => {
res.status(200).json({result});
})
};
我没有计入每月或每年的员工总小时。
现在我的结果是这样的:
{
"result": [
{
"_id": "5c5bb13c1d92482b148ed17b",
"attendance": [
{
"date": "2019-02-07T04:30:07.391Z",
"totalHours": 1,
"month": 2,
"year": 2019
},
{
"date": "2019-02-07T04:51:05.359Z",
"totalHours": 1,
"month": 2,
"year": 2019
},
{
"date": "2019-02-07T04:56:21.951Z",
"totalHours": 1,
"month": 2,
"year": 2019
}
]
},
{
"_id": "5c5fdb1781165a1e58115da7",
"attendance": []
},
{
"_id": "5c5fdd1738ec411b1849ce58",
"attendance": [
{
"date": "2019-02-10T08:14:01.201Z",
"totalHours": 1,
"month": 2,
"year": 2019
}
]
},
{
"_id": "5c5fdf6336e9ea24e0e69795",
"attendance": [
{
"date": "2019-02-10T08:23:14.180Z",
"totalHours": 1,
"month": 2,
"year": 2019
}
]
}
]
}
我需要聚合每个人的每月和每年的工作总小时数。现在我的结果看起来像如上。如何我总和小时的每一天?
回答如下:您可以使用下面聚集
db.collection.aggregate([
{ "$project": {
"totalHoursInThisMonth": {
{ "$let": {
"vars": { "date": {
"$filter": {
"input": "$attendance",
"as": "attend",
"cond": {
"$and": [
{ "$gte": ["$$attend.date", startOfMonth] },
{ "$lte": ["$$attend.date", endOfMonth] }
]
}
}
}},
"in": "$$date.totalHours"
}}
}
}}
])