nik*_*cub 15 mongodb mongodb-query aggregation-framework
在MongoDB中,使用$type,可以根据字段是否与BSON数据类型匹配来过滤搜索(请参阅DOCS).
例如.
db.posts.find({date2: {$type: 9}}, {date2: 1})
Run Code Online (Sandbox Code Playgroud)
返回:
{
"_id" : ObjectId("4c0ec11e8fd2e65c0b010000"),
"date2" : "Fri Jul 09 2010 08:25:26 GMT"
}
Run Code Online (Sandbox Code Playgroud)
我需要一个查询,告诉我该字段的实际类型是什么,对于集合中的每个字段.这可能与MongoDB有关吗?
sty*_*ane 21
从MongoDB 3.4开始,您可以使用$type聚合运算符返回字段的类型.
db.posts.aggregate(
[
{ "$project": { "fieldType": { "$type": "$date2" } } }
]
)
Run Code Online (Sandbox Code Playgroud)
产量:
{
"_id" : ObjectId("4c0ec11e8fd2e65c0b010000"),
"fieldType" : "string"
}
Run Code Online (Sandbox Code Playgroud)
Bha*_*aja 15
在mongo shell中键入以下查询
typeof db.employee.findOne().first_name
Run Code Online (Sandbox Code Playgroud)
句法
typeof db.collection_name.findOne().field_name
Run Code Online (Sandbox Code Playgroud)
好的,这里有一些可能有用的相关问题:
希望这可以让你开始.但是,我怀疑你会遇到这个请求的一些问题.这里有两个问题:
$type,但看起来您实际上不能gettype在字段上运行函数并将其映射回BSON类型.因此,如果您认为可以解决问题#1,那么您应该能够使用"获取所有字段名称"稍微改变来解决问题#2 .
它可能看起来像这样:
"map" : function() { for (var key in this) { emit(key, [ typeof value[key] ]); } }
"reduce" : function(key, stuff) { return (key, add_to_set(stuff) ); }
Run Code Online (Sandbox Code Playgroud)
所以基本上你会在map函数中发出key和type of key value(作为一个数组).然后从reduce函数中为每种类型添加唯一条目.
在运行结束时,您将拥有这样的数据
{"_id":[255], "name" : [1,5,8], ... }
当然,这都是很多工作,取决于你的实际问题,你可能只想确保(从你的代码)你总是放入正确的数据类型.在数据进入数据库之后查找数据类型肯定是一件痛苦的事.