declaring variables in MongoDB using $lookup with let and pipeline
It's the other way around. If you're running $lookup
on likes
collection then let
section's goal is to define variables that refer to the collection that you're running aggregation on. On the other hand you can refer to fields defined in likes
collection using single dollar sign inside of pipeline
. Try:
{ $lookup: { from: 'likes', let: { id: '$_id' }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ '$_id.userId', ObjectId('12345') ]}, { $eq: [ '$_id.postId', '$$id' ]} ] } } } ], as: 'liked' }}
EDIT: Please take a look at the docs
let
Optional. Specifies variables to use in the pipeline field stages. Use the variable expressions to access the fields from the documents input to the $lookup stage.The pipeline cannot directly access the input document fields. Instead, first define the variables for the input document fields, and then reference the variables in the stages in the pipeline.