MongoDB 在尝试插入整数时插入浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8218484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:19:44  来源:igfitidea点击:

MongoDB inserts float when trying to insert integer

mongodb

提问by daydreamer

   > 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?

如何让 Mongo 插入一个整数?

Thank you

谢谢

回答by Bernie Hackett

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

You can also use NumberLong.

您也可以使用 NumberLong。

回答by Grid Trekkor

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

一个稍微简单的语法(至少在 Robomongo 中)对我有用:

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

回答by Ethan. Zhang

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.

如果值类型已经是double,那么在使用NumberInt()或NumberLong()函数时,用$set命令更新值不能将值类型double改为int。因此,要更改值类型,它必须更新整个记录。

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

回答by Christian Horsdal

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:

嗯,它是 JavaScript,所以你在 'value' 中拥有的是一个数字,它可以是一个整数或一个浮点数。但是在 JavaScript 中并没有真正的区别。从学习 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 –253to 253.

数字数据类型

JavaScript 中的数字数据类型是浮点数,但它们可能有也可能没有小数部分。如果它们没有小数点或小数部分,它们将被视为整数——范围为 –2 53到 2 53 的以10 为底的整数。