Search code examples
node.jsmongodbnumbers

Query only round number in mongodb


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


Solution

  • 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!