Why $lookup requires $expr if I add pipeline and make a variable?

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:

      $lookup: {
        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"
      }
    },

Secondly, I am expecting pipeline should return count of documents instead of complete document, for this I’ve added a $count stage but that return count based on _id in a new array object
Please let me know how’s this possible

Is there any links you can share that confirms that

Starting with 5.0 you may use consise syntax to use localField:_id and foreignField:interactionId rather than

with

Since

does not use any of the let variable you could already to the $match you want.

Using the concise syntax your $lookup could be

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