【发布时间】:2019-07-03 22:20:52
【问题描述】:
我正在为考勤系统构建一个用于签入和签出员工的 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
}
]
}
]
}
我需要汇总每个人每月和每年的总工作时间。现在我的结果如上所示。如何计算每天的总小时数?
【问题讨论】:
-
你能发布样本集合和输出
-
我只得到按数组分组的月份和年份,并且没有输出总小时数@AnthonyWinzlet
-
如果您发布样本集合和输出,它将帮助我们生成输出
-
@AnthonyWinzlet 我已经编辑了我的结果现在或集合的样子。我需要按月汇总出勤率,以及每月的总小时数。