Join pipeline syntax

Hi,

in the “Basic Joins” lecture, the let operator is introduced. This operator defines a variable in the movies collection to be used in the comments pipeline.
It’s not really explained why the pipeline operator used the “$expr” operator.

I wanted to simplify the pipeline, but the following doesn’t work :

db.movies.aggregate([
{
“$match”: {
“_id”: ObjectId(“573a1390f29313caabcd418c”)
}
},
{
lookup" : { "from" : "comments", "let" : { "id" : "_id” },
“pipeline” : [
{
“$match” : {
“movie_id” : “$$id”
}
},
{
“$sort” : {
“date” : -1
}
}
],
“as” : “comments”
}
}
])

Here, I used a $match stage with a direct comparison : “movie_id” : “$$id”

The next pipeline does work :

db.movies.aggregate([
{
“$match”: {
“_id”: ObjectId(“573a1390f29313caabcd418c”)
}
},
{
lookup" : { "from" : "comments", "let" : { "id" : "_id” },
“pipeline” : [
{
“$match” : {
“$expr” : {
“$eq” : [ “$movie_id”, “$$id” ]
}
}
},
{
“$sort” : {
“date” : -1
}
}
],
“as” : “comments”
}
}
])

This time, I use the “$expr” operator, as in the video.

Is there a reason why the match stage in the nested pipeline doesn’t work in the first example ?

Thanks,

Bart

@Bart_22366

In MongoDB, the value with $$ prefix indicates it is a variable in aggregation expression. And the value with $ prefix indicates it refers to a field. They are totally different expression. It is the doc to explain it.

In terms of $expr, here is a quota from documentation,

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

Q Yang