Home > Software engineering >  how to pass dynamic value to $in in mongodb aggregation
how to pass dynamic value to $in in mongodb aggregation

Time:10-03

I have two collections 1 is campaigns and other is orders. I have to filter orders for each campaign. So what I am doing is that I'm fetching all the campaigns and after that I'm looking up for the orders that matches some specific criteria.

[
     { 
       $match: { type: 'FOLLOWUP' } 
     },
     {
       $lookup: {
         from: 'orders',
         as: 'orders',
         pipeline: [
           {
              $match: {
                 'status': { $in: '$activeFilter' }
              }
           }
         ]
       }
     }
]

In above example status contain some specific string and the activeFilter has array of string containing active status for that campaign. activeFilter is an array but I'm getting error that $in needs an array.

Any help would be appreciated.

CodePudding user response:

I assume activeFilter is not always an array. To make it dynamic try

{
    $match: {
       'status': { $in: {$cond: {
            if: { $isArray: '$activeFilter' }, 
            then: '$activeFilter', 
            else: ['$activeFilter'] ]
       } }
    }
}

CodePudding user response:

You are using Aggregation pipeline, and $in operator does not work the same in find() query and in Aggregation pipeline. In Aggregation pipeline, syntax is as follow:

{ $in: [ <expression>, <array expression> ] }

So, $in should have 2 parameters where value is the first one, and array is the second one. You should change your code like this:

"$match": {
  "$expr": {
    "$in": ["$status", "$activeFilter"]
  }
}

Working example

  • Related