mongodb 蒙哥。如何检查字段是否为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16357448/
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
Mongo. how to check if field is a number
提问by Andrei
How to select mongodb documents where field is a number?
如何选择字段为数字的mongodb文档?
Some examples of the content of this field: "2", "a", "Z", 3
此字段内容的一些示例:“2”、“a”、“Z”、3
回答by Adam Comerford
You can use the $typeoperator to select based on the BSON type of the field, which should get you what you want.
您可以使用$type运算符根据字段的 BSON 类型进行选择,这应该可以满足您的需求。
So, for example, to find all strings:
因此,例如,要查找所有字符串:
db.collection.find( { field: { $type : 2 } } )
Or, to find all doubles (which is usually what numbers get stored as from the shell thanks to the default Javascript behavior), you would use:
或者,要查找所有双打(由于默认的 Javascript 行为,这通常是从 shell 存储的数字),您可以使用:
db.collection.find( { field: { $type : 1 } } )
Since there are two types of integer (potentially) you would need to go with something like this:
由于有两种类型的整数(可能),您需要使用以下内容:
db.collection.find({$or : [{"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})
Finally then, to get all numbers, integer or double:
最后,要获取所有数字,整数或双精度数:
db.collection.find({$or : [{"field" : { $type : 1 }}, {"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})
回答by ebr
You can the type of a field bar
by using
您可以bar
使用字段的类型
typeof db.foo.findOne().bar
http://docs.mongodb.org/manual/core/shell-types/#check-types-in-shell
http://docs.mongodb.org/manual/core/shell-types/#check-types-in-shell
回答by Youssef Youssef
you can use the alias "number" instead:
您可以改用别名“number”:
{ field: {$type:"number"}}
回答by Tarun Vashisth
typeof
in mongo returns object
for array
type also. To check if a field is a Number
, run below query to see if it returns any result.
typeof
在蒙戈回报object
的array
类型也。要检查字段是否为Number
,请在查询下方运行以查看它是否返回任何结果。
db.foo.find('Object.prototype.toString.call(this.bar) === "[object Number]"')
db.foo.find('Object.prototype.toString.call(this.bar) === "[object Number]"')
You can also see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
您还可以查看https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
回答by Ashh
With the mongodb 4.4(upcoming), You can use $isNumber
pipeline operator to check whether the expression is integer or other BSON type.
使用 mongodb 4.4(即将发布),您可以使用$isNumber
管道运算符来检查表达式是整数还是其他 BSON 类型。
db.collection.aggregate([
{ "$project": {
"field": { "$isNumber": "$field" }
}}
])
And to get only the selected documents
并只获取选定的文档
db.collection.find({ "$expr": { "$anyElementTrue": { "$isNumber": "$field" }}})