Home > Net >  Aggregate where property minus property is bigger than value
Aggregate where property minus property is bigger than value

Time:12-28

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)

CodePudding user response:

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

  • Related