我在mongodb中有一个集合,如下所述。
{ "UserID" : "User1",
"TaskId" : "Task1",
"SubTaskID" : "Subtask1",
"StartDate" : ISODate("2016-02-06T05:00:00Z"),
"EndDate" : ISODate("2016-02-06T05:00:00Z"),
"Hours" : 8, //no of hours worked between StartDate and EndDate on the subtask
"Department:"DEPT1"; //I can have multiple departments
"__v" : 0}
现在,我想计算startdate和enddate之间的总工作小时数以及该持续时间内所有成员在该部门中为该子任务输入的总小时数。我的输出应该看起来像
{
"TaskId":"TaskId1",
"UserId":"UserId1",
"startDate":"2016-02-06",
"endDate":"2016-02-06",
"totalHours": 10.0,
"deptTotalHours":100.0,
"subtasks": [
{
"SubTaskID": "SubTask1",
"totalHours": 4.0,
"deptTotalHours":40.0
},
{
"SubTaskID": "SubTask2",
"totalHours": 6.0,
"deptTotalHours":60.0
}]
}
我尝试使用$ match,$ project和$ group但是我无法以指定的格式获得响应。有人可以建议我如何以上面指定的格式获得回复吗?
答案 0 :(得分:0)
使用以下管道操作,它将为您提供子任务所需的所有信息。然后,所有子任务中的totalHours,deptTotalHours只是子任务结果中的记录总和(您可以在应用程序中执行此操作)。其余信息可作为输入本身的一部分提供。
pipeline = [
{
$match: {} // Add criteria based on start and end date, don't include UserID criteria here
},
{
$group: {
_id: '$SubTaskID',
deptTotalHours: {$sum: '$Hours'},
totalHours: {$sum: {$cond:[
{$eq: ['$UserID', inputUserId]},
'$Hours',
0.0
]}
}
}
}
];