MongoDB tip, db.col.insert integer becomes double by default

This post is using MongoDB version 3.2.11

I ran into this issue after we performed db.col.insertMany and everything seemed to work fine without a problem, all records were there... until application connected to it and we started seeing a bunch error. 

We noticed that the error is indicating some sort of type error, so we began to investigate, 

Through a simple test we can see how this version of mongod behaves when we perform a simple insert of an integer

db.test.insert({a:1})

and we look into what we had inserted

db.test.find().pretty()
{
    "_id" : ObjectId("59724963cd6857bf00a347fb"),
    "testInt" : 1
}

the output seems to have indicated it's stored correctly as an integer, but when we look deeper

We can see the type is stored as double instead of int

Therefore, to insert either the int32 or int64 type, we should do

db.test.insert({b:NumberInt(1)})  

for int32, or

db.test.insert({c:NumberLong(1)})

for int64.

And now we see the number being stored correctly as int




This behavior is due to mongo shell to treat all numbers as floating-point values, instead, use NumberLong() or NumberInt() to insert integers. They represent numbers in int64 or int32 respectively.


Comments

Popular posts from this blog

MongoDB tip: 4 ways to modify replica set configuration

MongoDB Tips: Kill long running processes

MongoDB Quick Note: BI Connector Issue