Home > Back-end >  Query only round number in mongodb
Query only round number in mongodb

Time:09-06

every one.

I would like to know if it's possible in mongodb to query only round number.

I have a collection where my documents have a field: amount and this field is a number.

But I would like to get only documents where fields is a round number.

so I saw there is a $round but this round the number and I want only round number not rounded :P

Does anyone if you can do that with query in mongodb ?

thanks a lot

CodePudding user response:

I would use $mod (num % 1) and check that the value is 0, like so:

db.collection.find({
  $expr: {
    $eq: [
      {
        $mod: [
          "$num",
          1
        ]
      },
      0
    ]
  }
})

Mongo Playground

CodePudding user response:

You can use a tolerance to do something like this:

db.collection.aggregate([
  {$match: {
      $expr: {
        $lte: [
          {$abs: {$subtract: ["$amount", {$round: "$amount"}]}},
          0.000001
        ]
      }
    }
  }
])

See how it works on the playground example

*EDIT: The $round here is a fix by @rickhg12hs to my former $floor. Thanks!

  • Related