244
votes
   > 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

4
which version of mongodb do you use ? - kamaradclimber
note that in my case , when i wanted to {$set:{val:NumberInt(0)}} at some "val" that's already set as Long , it didn't change it. I had to first change it to some other value , then change it back to 0 , for the NumberInt(0) to take effect - kommradHomer
I had same problem, after realizing I had mistakenly changed an int32 to double, setting it back using NumberInt() did not fix the type unless I first changed to a different value. - user1055568

4 Answers

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

You can also use NumberLong.

19
votes

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

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

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)
-12
votes

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.