简体   繁体   English

MongoDB int64和JavaScript

[英]MongoDB int64 and JavaScript

I write a Long value from Java to MongoDB which stores it as an int64. 我将Java的Long值写入MongoDB,并将其存储为int64。 Browsing the data via RoboMongo I can see the following value: 通过RoboMongo浏览数据,我可以看到以下值:

nanoTimestamp: 1467100788819818000

I then fetch the values in JS (using meteor) and I end up with the following object: 然后,我获取JS中的值(使用流星),最终得到以下对象:

Object {_bsontype: "Long", low_: 932437528, high_: 341586032}

How can I work with this type on the client side? 如何在客户端使用这种类型?

The problem here is that JavaScript's number type is IEEE-754 double-precision binary floating point, which has roughly 15 digits of decimal precision. 这里的问题是JavaScript的数字类型是IEEE-754双精度二进制浮点数,其十进制精度大约为15位。 So although you can get a JS number from that BSON Long: 因此,尽管您可以从该BSON Long中获得一个JS号:

// May not be precise!
var num = l.high_ * Math.pow(2,32) + l.low_;

...it won't be exactly the same number (in your example case, it'll come out 1467100837142847000). ...不会是完全相同的数字(在您的示例情况下,它将显示为1467100837142847000)。

If it's okay that it's imprecise (we are talking about nanoseconds here), you're all set. 如果可以做到不精确(在这里我们谈论的是纳秒级),那么一切都准备就绪。

If not, and you need to deal with these in JavaScript, you might consider recording them as a string rather than Long: 如果不是这样,并且您需要使用JavaScript处理它们,则可以考虑将它们记录为字符串而不是Long:

nanoTimestamp: "1467100788819818000"

...and then using one of the several JavaScript "big number" libraries that can do operations on arbitrarily-large integers or floating-point numbers. ...然后使用可以对任意大的整数或浮点数进行运算的多个JavaScript“大数”库之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM