嗨,我有这种收藏。
[{
"_id" : ObjectId("5d7e56cc61f05d22ff7ee318"),
"Emp No" : "0088P2C",
"Emp Name" : "MANISHA JHA",
"Card No" : "2076",
"Department" : "THBS",
"Att Date" : "03-Jun-2019",
"In Time" : "03-Jun-2019 10:53",
"Out Time" : "03-Jun-2019 18:13",
"Status" : "P ",
"Late By " : "01:53",
"Early By " : "00:00",
"Total Hour" : "07:20",
"OT Hour" : "00:00",
"Location" : "Consolidated",
"id" : "1c4bdbcd0f57c17a7160697266e9b371"
},
{
"_id" : ObjectId("5d7e56cc61f05d22ff7ee319"),
"Emp No" : "0088P2C",
"Emp Name" : "MANISHA JHA",
"Card No" : "2076",
"Department" : "THBS",
"Att Date" : "04-Jun-2019",
"In Time" : "04-Jun-2019 09:50",
"Out Time" : "04-Jun-2019 15:33",
"Status" : "P ",
"Late By " : "00:50",
"Early By " : "02:27",
"Total Hour" : "05:43",
"OT Hour" : "00:00",
"Location" : "Consolidated",
"id" : "a54e78844d0c27bd15607feb50aa272b"
}]
我想计算total hours
。i这样的聚合查询employees
并获取总小时数
await Attendance.aggregate(
[
{$match: {Department: "THBS"}},
{
$group: {
_id: '$Emp No',
totalTime: {$sum: "$Total Hour"},
data: {$addToSet: {attendance: "$Att Date", Status: "$Status", id: "$id"}}
}
},
{$project: {'Emp No': '$_id', _id: 0, data: 1, totalTime: 1}}
])
当前total hour
来自此查询0
。预期应该是12.63
答案 0 :(得分:1)
尝试使用$toInt,$substr和$multiply将存储为字符串的Total Hour
转换为分钟。然后,您可以$sum将该值转换为使用$divide的小时数:
db.collection.aggregate([
{$match: {Department: "THBS"}},
{
$addFields: {
TotalMinutes: {
$add: [
{ $toInt: { $substr: [ "$Total Hour", 3, 2 ] } },
{ $multiply: [ { $toInt: { $substr: [ "$Total Hour", 0, 2 ] } }, 60 ] }
]
}
}
},
{
$group: {
_id: '$Emp No',
totalTime: {$sum: "$TotalMinutes"},
data: {$addToSet: {attendance: "$Att Date", Status: "$Status", id: "$id"}}
}
},
{
$project: {
'Emp No': '$_id',
_id: 0,
data: 1,
totalTime: { $add: [
{ $toInt: { $divide: [ "$totalTime", 60 ] } },
{ $divide: [ { $mod: [ "$totalTime", 60 ] }, 100 ] }
]
}
}
}
])
编辑:在这种情况下,12.63等于13小时3分钟