Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any gotchas when using $inc with float values in MongoDB?

Tags:

mongodb

Firstly, is it fully supported to increment by floating values?

What level of floating-point precision is maintained?

like image 835
Nic Cottrell Avatar asked Oct 19 '25 15:10

Nic Cottrell


2 Answers

MongoDB does support incrementing by floating point values. This will cause the stored value to be converted to floating point if it is currently some other numeric type, which can lead to rounding errors if the previous value was a very large 64-bit integer.

All of the standard caveats involving floating point numbers apply. MongoDB, like JavaScript interpreters in web browsers, stores IEEE double precision (64-bit) floating point values. These values have 53 bits of precision. Intermediate calculations may be computed using 80-bit long doubles, but the final result is always stored as a 64-bit double precision floating point value.

like image 135
Andy10gen Avatar answered Oct 22 '25 05:10

Andy10gen


I've run into issues in the shell, when using very big numbers. JavaScript would round down, so the increment wouldn't happen and it would go into an infinite loop. I had to force it to use NumberLong(), to get around the problem. To be fair, I wasn't explicitly using a float type, but I believe that is the default in JavaScript--I was using it as a whole number (a count).

This shouldn't be an issue in a non-JavaScript language driver, as far as I know.

like image 24
Eve Freeman Avatar answered Oct 22 '25 03:10

Eve Freeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!