5

How can I perform precise arithmetic on NumberLong values in the Mongo shell? It's my understanding that Javascript only has one numeric type - number - typically limited to 54-bit floating-point precision.

Direct arithmetic using (e.g.) standard addition shows demoting coercion to lower-precision type:

> NumberLong("123456789012345678")+NumberLong("1") 
123456789012345680
> NumberLong("123456789012345678")+NumberLong("2")
123456789012345680

I can see how to extract portions of a NumberLong using string representations, but this seems inefficient and is not useful for such arithmetic operations as increment or divide.

RubyTuesdayDONO
  • 2,350
  • 2
  • 25
  • 37

1 Answers1

2

MongoDB uses the BSON 64 bit Int type (Mongo type code 18) for NumberLong. The db kernel can perform precise arithmetic on these elements (kernel written in C++) through doing update operations but if you want to do this in the javascript shell you'll need a library like this one from Google.

Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
jpredham
  • 2,149
  • 1
  • 23
  • 37
  • the other piece of the puzzle is getting the top/bottom 32 bits, which appear to be private (see JIRA [SERVER-4141](https://jira.mongodb.org/browse/SERVER-4141)). i should be able to proceed from here - thanks! – RubyTuesdayDONO Dec 21 '11 at 18:15
  • It really su**s those arithmetic operations aren't exposed. It makes M/R jobs dealing with NumberLong such an hassle... – Vincent Aug 09 '14 at 19:59
  • @jpredham What is the library for that NumberLong arithmetics? Your link is broken! – Hamid Alaei Apr 11 '18 at 12:23
  • 1
    @HamidAlaei Looks like Google moved the closure library to github: https://google.github.io/closure-library/api/goog.math.Long.html. However, this answer is now over 6 years old and I'm not sure if it's still relevant. – jpredham Apr 11 '18 at 15:58