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

Aggregate where property minus property is bigger than value

I try to aggregate documents where firstValue minus secondValue is bigger than 2

Example documents:

[
 {
   "firstValue": 6,
   "secondValue": 3
 },
 {
  "firstValue": 6,
  "secondValue": 5
 },
 {
  "firstValue": 6,
  "secondValue": 7
 }
]

Query should return only first element (6-3 = 3, 3>2)

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

>Solution :

You can use simple find for it:

db.collection.find({
  "$expr": {
    $gt: [
      {
        "$subtract": [
          "$firstValue",
          "$secondValue"
        ]
      },
      2
    ]
  }
})

find fiddle

Or use this expression into aggregate:

db.collection.aggregate({
  "$match": {
    "$expr": {
      $gt: [
        {
          "$subtract": [
            "$firstValue",
            "$secondValue"
          ]
        },
        2
      ]
    }
  }
})

aggregate fiddle

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