简体   繁体   中英

MongoDB int64 and JavaScript

I write a Long value from Java to MongoDB which stores it as an int64. Browsing the data via RoboMongo I can see the following value:

nanoTimestamp: 1467100788819818000

I then fetch the values in JS (using meteor) and I end up with the following object:

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. So although you can get a JS number from that BSON Long:

// 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).

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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