I am using aggregation and doing lookup after that need to use lookup value in match query. Is that possible?

Here I am giving sample query of my question. let me know what is the way to achieve this type of thing

db.feedposts.aggregate([
    {
        $lookup: {
          from: 'friends',
          pipeline: [
            {
              $match: {
                $and: [
                  {
                    $or: [
                      { from: { $eq: ObjectId('634d06ae9787d60afbddff96') } },
                      { to: { $eq: ObjectId('634d06ae9787d60afbddff96') } },
                    ],
                  },
                  { reaction: 3 },
                ],
              },
            },
            { $group: { _id: null, from: { $addToSet: '$from' }, to: { $addToSet: '$to' } } },
            {
              $project: {
                _id: 0,
                ids: { $setUnion: ['$from', '$to'] },
              },
            },
          ],
          as: 'friendsDetails',
        },
      },
      { $unwind: '$friendsDetails' },
      {
          $match: {
              userIds: {
                  $in: '$$friendDetails'
              }
          }
      }
    ])

Currently this query gives error but here I am giving idea what I need to achieve

Hi @ronakd ,.

I think it should work with $expr in the match:

{
        $match: {
          $expr: {
    
              {
                $in: [
                  '$userIds',
                   {$ifNull : ['$friendDetails.ids',[]]}
                ]
              }
     }}
}

I haven’t tested this yet but it should allow you to use a field as a value in an expression…

Let me know if that works.

Thanks
Pavel

1 Like

Thanks @Pavel_Duchovny . it works for me

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.