Alexander Shold
Alexander Shold

Reputation: 45

$match in lookup stage without removing local documents in mongoDB

Right now I have a lookup stage that matches a collection of answers with their respective questions. The problem I'm having is that on the $match if the question does not having a matching answer document in the lookup collection it is removed from the results of the aggregation. How can I avoid this?

  {
    $lookup: {
      from: 'groupansphotos',
      let: { question_id: '$questions._id' },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ['$_id', '$$question_id'] },
          },
        },
        { $unwind: '$answers' },
        { $match: { 'answers.reported': { $lt: 1 } } },
        { $sort: { 'answers.helpful': -1 } },
        { $limit: 2 },
        {
          $project: {
            _id: 0,
            k: { $toString: '$answers._id' }, // k
            v: '$$ROOT.answers', // v
          },
        },
      ],
      as: 'answers',
    },
  },

Upvotes: 1

Views: 113

Answers (0)

Related Questions