Long Numbers Are Truncated in MongoDB Shell
MongoDB is notorious for it's quirks; in this short read, MVB Ricci Gian Maria explains how he solved this problem with the popular document store.
Join the DZone community and get the full member experience.
Join For Freelet’s try this simple code in a mongo shell:
db.testcollection.insert({"_id" : 1, "value" : numberlong(636002954392732556) })
db.testcollection.find()
what you expect is that mongo inserted one record and then that record is returned. actually, a record is inserted, but the return value can surprise you . here is the output i got from robomongo:
{
"_id" : 1.0,
"value" : numberlong(636002954392732544)
}
property “value” has not the number you inserted, the number seems to be rounded and some precision is lost , even if it is a numberlong and 636002954392732556 is a perfectly valid int64 number. this behavior surprised me because i’m expecting rounding to happen only with double, not with an int64.
actually, a double precision floating point number that uses 64 bit for representation, is not capable of having the same precision of an int64 number, because part of those 64 bits are used to store an exponent. if you try to represent a big number like 636002954392732556 in double floating point precision some rounding is going to happen. if you are not convinced, try this online converter to convert 636002954392732556, here is the result:
figure 1: floating point number rounding
this confirms that my problem was indeed caused by rounding because the number is somewhat converted to floating point format, even if i used numberlong bson extension to specify that i want a long and not a floating point type.
the reason behind this is subtle. let's try another example, just type numberlong(636002954392732556) in a mongo shell (i used robomongo), and verify the result.
figure 2: numberlong gets rounded directly from the shell.
this unveils the error, the number is returned surrounded with quotes, and this suggests that quotes are the problem. in javascript, every number is a double, and if you write numberlong(636002954392732556) javascript translates this to a call to the numberlong function passing the number 636002954392732556 as an argument . since every number in javascript is a double, the number 636002954392732556 gets rounded before it is passed to the numberlong function.
if you surround the number with quotes, you are passing a string to numberlong—in this scenario, rounding does not occur and the numberlong function is perfectly capable of converting the string to a number.
* in mongo shell, always use quotes when you create numbers with numberlong.
actually, this error only happens with really big numbers, but you need to be aware of this if you are creating a script that uses numberlong.
related refcard:
Published at DZone with permission of Ricci Gian Maria, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments