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

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

Mongo. how to check if field is a number

mongodbmongodb-query

提问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 barby 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

typeofin mongo returns objectfor arraytype also. To check if a field is a Number, run below query to see if it returns any result.

typeof在蒙戈回报objectarray类型也。要检查字段是否为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 $isNumberpipeline 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" }}})