Home > Enterprise >  MongoDB aggregate $match using dynamic field path
MongoDB aggregate $match using dynamic field path

Time:07-02

I want to match documents in my pipeline based on whether the field to match is contained within an array that is within my documents.

Example document to match:

{
  'wishlist': ['123','456','789'],
  'productId': '123'
}

Example match aggregation:

{
   $match: {
        'productId': {$in: '$wishlist'}
   }
}

This isn't working - error is '$in needs an array' - but '$wishlist' is an array? so clearly the stage isn't picking up the path reference.

How would I get something like this to work? Thanks!

CodePudding user response:

If you want to match the internal field of the document, you can use $expr expression operator, and I see that field has an array value then you have to use $in operator's aggregation syntax,

{
   $match: {
        $expr: { 
            $in: ["$productId", '$wishlist'] 
        }
   }
}
  • Related