问题描述
如何在Mongo shell中对NumberLong值执行精确算术运算?我的理解是Javascript只有一种数字类型 - 数字
- 通常限于54位浮点精度。
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
我可以看到如何使用字符串表示提取NumberLong的部分,但这似乎效率低,并且对增量或除法等算术运算没有用。
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.
推荐答案
MongoDB使用()为NumberLong。 db内核可以通过执行更新操作对这些元素(用C ++编写的内核)执行精确算术,但是如果你想在javascript shell中执行此操作,则需要一个像。
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.
这篇关于Mongo shell中的NumberLong算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!