MongoDB inserts float when trying to insert integer

Mongodb

Mongodb Problem Overview


   > db.data.update({'name': 'zero'}, {'$set': {'value': 0}}) 
   > db.data.findOne({'name': 'zero})
    {'name': 'zero', 'value': 0.0}  

How do I get Mongo to insert an integer?

Thank you

Mongodb Solutions


Solution 1 - Mongodb

db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})

You can also use NumberLong.

Solution 2 - Mongodb

A slightly simpler syntax (in Robomongo at least) worked for me:

db.database.save({ Year : NumberInt(2015) });

Solution 3 - Mongodb

If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.

var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)

Solution 4 - Mongodb

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

> The Number Data Type > >Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaydreamerView Question on Stackoverflow
Solution 1 - MongodbBernie HackettView Answer on Stackoverflow
Solution 2 - MongodbGrid TrekkorView Answer on Stackoverflow
Solution 3 - MongodbEthan. ZhangView Answer on Stackoverflow
Solution 4 - MongodbChristian HorsdalView Answer on Stackoverflow