Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
              ]
            }
          ]
        }
      }
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading