skip to Main Content

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 😛

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

thanks a lot

2

Answers


  1. 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!

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search