Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumberLong arithmetic in the Mongo shell

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.

like image 251
RubyTuesdayDONO Avatar asked Nov 04 '22 09:11

RubyTuesdayDONO


1 Answers

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.

like image 165
jpredham Avatar answered Nov 09 '22 13:11

jpredham