返回 MongoDB 中字段的实际类型
在 MongoDB 中,使用 $type
,可以根据字段是否与 BSON 数据类型匹配来过滤搜索(请参阅 DOCS)。
例如。
db.posts.find({date2: {$type: 9}}, {date2: 1})
返回:
{
"_id" : ObjectId("4c0ec11e8fd2e65c0b010000"),
"date2" : "Fri Jul 09 2010 08:25:26 GMT"
}
我需要一个查询来告诉我集合中每个字段的字段的实际类型是什么。 MongoDB 可以做到这一点吗?
In MongoDB, using $type
, it is possible to filter a search based on if the field matches a BSON data type (see DOCS).
For eg.
db.posts.find({date2: {$type: 9}}, {date2: 1})
which returns:
{
"_id" : ObjectId("4c0ec11e8fd2e65c0b010000"),
"date2" : "Fri Jul 09 2010 08:25:26 GMT"
}
I need a query that will tell me what the actual type of the field is, for every field in a collection. Is this possible with MongoDB?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 MongoDB 3.4 开始,您可以使用
$type
聚合运算符返回字段的类型。产生:
Starting from MongoDB 3.4, you can use the
$type
aggregation operator to return a field's type.which yields:
中输入以下查询
在 mongo shell语法
type the below query in mongo shell
Syntax
好的,以下是一些可能有帮助的相关问题:
使用 map-reduce 获取集合中的所有字段名称。
这是列出所有可能字段的递归版本。
希望这可以帮助您开始。但是,我怀疑您会遇到此请求的一些问题。这里有两个问题:
$type
进行查询,但看起来您实际上无法在字段上运行gettype
函数并将其映射回 BSON 类型。因此,如果您假设您可以解决问题#1,那么您应该能够使用“获取所有字段名称”的细微变化来解决问题#2。
它可能看起来像这样:
所以基本上你会在映射函数中发出
键
和键值类型
(作为数组)。然后,您可以从reduce 函数中为每种类型添加唯一的条目。运行结束时,您将得到如下数据
{"_id":[255], "name" : [1,5,8], ... }
当然,这就是全部大量的工作,根据您的实际问题,您可能只想确保(从您的代码中)始终输入正确类型的数据。数据入库后查找数据类型绝对是一件痛苦的事情。
OK, here are some related questions that may help:
Get all field names in a collection using map-reduce.
Here's a recursive version that lists all possible fields.
Hopefully that can get you started. However, I suspect that you're going to run into some issues with this request. There are two problems here:
$type
, but it doesn't look like you can actually run agettype
function on a field and have that maps back to the BSON type.So if you assume that you can solve problem #1, then you should be able to solve problem #2 using a slight variation on "Get all field Names".
It would probably look something like this:
So basically you would emit the
key
and thetype of key value
(as an array) in the map function. Then from the reduce function you would add unique entries for each type.At the end of the run you would have data like this
{"_id":[255], "name" : [1,5,8], ... }
Of course, this is all a lot of work, depending on your actual problem, you may just want to ensure (from your code) that you're always putting in the right type of data. Finding the type of data after the data is in the DB is definitely a pain.
利用 styvane 查询,我添加了一个 $group 列表,以便在我们有不同的数据类型时更容易阅读。
并得到这样的结果:
Taking advantage of the styvane query, I added a $group listing to make it easier to read when we have different data types.
And have this result:
注意到
a=5;a.constructor.toString()
打印function Number() { [native code] }
,可以执行类似以下操作:Noting that
a=5;a.constructor.toString()
printsfunction Number() { [native code] }
, one can do something similar to: