节点js,Mongoose计算总和并返回多个字段

我在下面提到的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之间的总工作小时数,以及该时间段内所有成员在该部门中为该子任务input的总小时数。 我的输出应该看起来像

 { "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 }] } 

我已经尝试过$匹配,$项目和$组,但我不能以指定的格式得到响应。 有人可以请我build议我如何获得在上述指定格式的答复?

使用下面的stream水线操作可以为您提供子任务所需的全部信息。 然后在所有子任务中的totalHours,deptTotalHours只是子任务结果中的logging总和(您可以在应用程序中执行此操作)。 其余的信息可以作为你的input本身的一部分。

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 ]} } } } ];