long number is not updating properly in mongodb

1.4k views Asked by At

I tried to update a field in a document which was long integer. But it was updated to the value '14818435007969200' instead of '14818435007969199'.

db.getCollection('title').updateMany({},
{$set:{'skillId':[NumberLong(14818435007969199)]}})

db.getCollection('title').find({})

{
    "_id" : ObjectId("5853351c0274072315da2426"),
    "skillId" : [ 
        NumberLong(14818435007969200)
    ]
}

Is there any solution? I am using robomongo 0.9.0.

2

There are 2 answers

0
s7vr On BEST ANSWER

The mongo shell treats all numbers as floating point values. So while using the NumberLong() wrapper pass the long value as string or risk the loss for precision or conversion mismatches.

This should work as expected.

db.getCollection('title').updateMany({},
{$set:{'skillId':[NumberLong("14818435007969199")]}})

Just to demonstrate for example.

So when converting 14818435007969199 to binary base 2 value you get 110100101001010100100111000010110001101111011110110000 which when converted back to base 10 is 14818435007969200

You can checkout the floating point arithmetic for more details.

0
Sameer Kazi On

here is an example with where condition in the query

 db.CustomerRatibs.update(
    { custRatibId:'8b19bfdbac7b468b9c3edafc37ad5409' },
    { $set:
       {
        uAt : NumberLong(1536581726000)
       }
    },
    {
        multi:false
    }
 )