我有两个收藏:

人物集合:

{
   _id: ObjectId,
   name: String,
   employments: [
      {
         start: Date,
         end: Date
      }
   ]
}


营业时间:

{
   _id: ObjectId,
   people: ObjectId,
   workDate: Date,
   workHours: Number
}


在我的Mongoose / Express控制器中,如何在每个工作对象中创建一个新字段totalHrs,并用findById返回小时数总和。workHours中workDate在工作的开始和结束之间?例如就像是:

{
   _id: ObjectId,
   name: String,
   employments: [
      {
         start: Date,
         end: Date,
         totalHrs: Number /*(Sum of hours.workHours)*/
      }
   ]
}

最佳答案

经过研究和学习,我自己解决了。

我做到了:

db.people.aggregate([
    {
        $lookup: {
            from:"hours",
            localField:"_id",
            foreignField:"people",
            as:"hours"
        }
    },

    {
        $unwind:"$hours"
    },
    {
        $addFields: {
            isInRange: {$and: [
                {$lt: ["$employments.start", "$hours.workDate"]},
                {$gte: ["$employments.end", "$hours.workDate"]},
                ]
            }
        }
    },
    {
        $match: {"isInRange":true},
    },
    {
        $group: {
            _id: "$_id",
            name: {$first: "$name"},
            totalHours: {$sum: "$hours.workHours"},
        }
    }

]);

10-06 11:58