将不相关的对象保留在mongodb聚合中

时间:2018-12-05 18:32:45

标签: javascript mongodb mongoose aggregate

我正在尝试对users集合进行汇总,而不是对另一个集合$lookup进行usersurveystatuses来查找该用户是否已完成调查。这可以正常工作,但它仅投影具有匹配调查的用户。即使调查无关,我如何保留所有用户。 代码:

db.collection('users')
      .aggregate([
        {
          $match: { roles: { $in: ['user'] } },
        },
        {
          $lookup: {
            from: 'usersurveystatuses',
            localField: '_id',
            foreignField: 'user_id',
            as: 'completedSurveys',
          },
        },
        {
          $unwind: {
            path: '$completedSurveys',
          },
        },
        {
          $match: {
            'completedSurveys.status': 'completed',
          },
        },
        {
          $group: {
            _id: '$_id',
            name: { $first: '$firstname' },
            surname: { $first: '$lastname' },
            credits: { $first: '$credits' },
            completedSurveys: { $push: '$completedSurveys' },
          },
        },
        {
          $project: {
            _id: 1,
            name: 1,
            surname: 1,
            credits: 1,
            completedSurveys: 1,
          },
        },
      ])
      .toArray()
      .then(users => {
        console.log(users)
      })

结果仅返回已完成调查的用户。

[ { _id: 5be98fa0b02eed1b2a17ca54,
    name: 'User',
    surname: 'User',
    credits: 0,
    completedSurveys: [ [Object], [Object] ] } ]

0 个答案:

没有答案