Not able to use _id in a lookup pipeline

I have two collections projects and products, where products has a field project, which refers to the projects._id field.

I am using this aggregation $lookup to find the products that belong to a specific project

{
  from: 'products',
  let: { id: '$_id'},
  pipeline: [{
    $match: { project: '$$id' }
  }],
  as: 'products'
}

the resulting products field is always empty, and I don’t understand why.

(I know I can use the other $lookup variant with foreignField localField, but I think I need the pipeline because I want to add more clauses to the $match)

Is your field in the products collection really named project?

yes, I am a afraid it is.

I just when back to documentation at https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ and found:

NOTE

To reference variables in pipeline stages, use the "$<variable>" syntax.

The let variables can be accessed by the stages in the pipeline, including additional $lookup stages nested in the pipeline .

Special attention to the sentence A $match stage requires the use of an $expr operator to access the variables.

3 Likes

Thank you, it works now.

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