Search code examples
javascriptmongodbmongodb-queryaggregation-frameworkaggregate

how to add a OR condition inside AND in $filter of mongodb aggregate


Below is a block from my aggregate query,

{
          $addFields: {
            destinations: {
              $filter: {
                input: "$destinations",
                cond: {
                  $and: [
                    {
                      $or: [
                        {
                          "$$this.reported_at": {
                            $exists: false
                          }
                        },
                        {
                          "$$this.reported_at": {
                            $eq: null
                          }
                        }
                      ],
                    },
                    {
                      $eq: [
                        "$$this.type",
                        1
                      ]
                    }
                  ]
                }
              }
            }
          }
        },

which when run is throwing the below error

query failed: (InvalidPipelineOperator) Invalid $addFields :: caused by :: Unrecognized expression '$$this.reported_at'

Although reported_at is another property just like type inside the destinations array. When I remove the object containing the OR condition, its not throwing an error. Please help me resolve this.

Thanks in advance


Solution

  • In the $filter cond field, you have to use the expression operator. Your query should be as below:

    {
      $addFields: {
        destinations: {
          $filter: {
            input: "$destinations",
            cond: {
              $and: [
                {
                  $or: [
                    {
                      $eq: [
                        "$$this.reported_at",
                        undefined
                      ]
                    },
                    {
                      $eq: [
                        "$$this.reported_at",
                        null
                      ]
                    }
                  ],
                  
                },
                {
                  $eq: [
                    "$$this.type",
                    1
                  ]
                }
              ]
            }
          }
        }
      }
    }