2

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

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

3 Comments

But I use $abs
Got you and updated the answer accordingly. Thanks @rickhg12hs
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.