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

check the second value if the first is null in Mongodb aggregation

I have this object in my products schema:

{
  price: {
    v1: number,
    v2: number
  }
}

price.v1 is always required and not null, on the other hand price.v2 is not required and can be null.

I want to search for the products with price > 20.

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

If the price.v2 is null I need to check if the price.v1 > 20.

If the price.v2 is not null I need to check if price.v2 > 20.

How can i do this in a aggregation?

>Solution :

Work with $ifNull operator. The query will filter with price.v2 first when it is not null. Otherwise, it will use price.v1 to filter.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            $ifNull: [
              "$price.v2",
              "$price.v1"
            ]
          },
          20
        ]
      }
    }
  }
])

Demo @ Mongo Playground

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