skip to Main Content

I’ve been trying to get data from collection without using $expr inside $match pipeline stage because it’s less performant and compared to simple $match

Here’s a piece of code I’ve been working on:

        from: 'messages',
        let: { "iId": "$_id" },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ["$interactionId", '$$iId'] },
                  { $eq: ["$author.role", 'agent'] }
                ]
              }
            }
          }
        ],
        as: "messages"
      }
    },

I am expecting to change this condition to simply this:

    {
      $lookup: {
        from: 'messages',
        pipeline: [
          {
            $match: {
              "interactionId": "$_id",
              "author.role": "agent"
            }
          },
        ],
        as: "messages"
      }
    },

2

Answers


  1. One option might be:

    ...
    {
      $lookup: {
        from: 'messages',
        localField: "_id",
        foreignField: "interactionId",
        pipeline: [
          {
            $match: {
              "author.role": "agent"
            }
          }
        ],
        as: "messages"
      }
    },
    ...
    
    Login or Signup to reply.
  2. pipeline inside $lookup doesn’t have any reference to parent collection data, it only has the reference to current data.
    so you always have to use let variables to access any data from the parent

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search