在Mongoose中,如何聚合数组中的引用?

时间:2017-11-19 16:32:41

标签: node.js mongodb express mongoose

我有两个系列:

人物收藏:

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

小时收集:

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

在我的Mongoose / Express控制器中,如何在每个就业对象中创建一个新字段 totalHrs ,以便与findById一起返回,其中它是hours.workHours的总和,其中workDate位于start和end之间在就业?例如类似的东西:

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

1 个答案:

答案 0 :(得分:0)

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

我是这样做的:

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"},
        }
    }

]);