Basic join - $lookup

Hi,
I have a question about this lesson:


at 01:21,
we use this pipeline:
pipeline: [
  { $match:
    { $expr: { $eq: ["$movie_id", "$$id"]}}
  }
]

my question is why is it not possible to replace it by this:

pipeline: [
  { $match:
    { movie_id: "$$id"}
  }
]

Thanks,
Rafael,

Hi @Rafael_Green, as mentioned here:

$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. Instead, use a $expr query expression to include aggregation expression in $match .

Hence you should use a $expr while doing match in these kind of pipelines.
I hope it helps.

Thanks & Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

1 Like

Hi @SourabhBagrecha,
Thanks for the answer but I still don’t understand what is the difference between a regular pipeline and the pipeline inside the $lookup stage.
To be more specific,
This code is working fine:

comments.aggergate([
  {
    '$match': {
      'movie_id': new ObjectId('573a139af29313caabcf0d74')
    }
  }
])

but this code doesn’t work as expected (by me):

movies.aggregate([
  {
    '$match': {
      '_id': new ObjectId('573a139af29313caabcf0d74')
    }
  }, {
    '$lookup': {
      'from': 'comments', 
      'let': {
        'id': '$_id'
      }, 
      'pipeline': [
        {
          '$match': {
            'movie_id': '$$id'
          }
        }, {
          '$sort': {
            'date': -1
          }
        }
      ], 
      'as': 'comments'
    }
  }
])

what is wrong with the last pipeline?
Thanks,

After digging a little more in the documentation I found this in the documentation of $lookup:

A $match stage requires the use of an $expr operator to access the variables. $expr allows the use of aggregation expressions inside of the $match syntax.

Without the use of the $expr operator, $match can refer to fields in a document but cannot access variables defined by a $lookup let clause.

2 Likes

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