按数组类型查询-MongoDB [英] Query by array type - MongoDB
本文介绍了按数组类型查询-MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须按类型查询我的mongoDB集合.
假设我有这两个 hello 集合的文档:
I have to query my mongoDB collection by type.
Suppose I have these two documents of hello collection:
{
"_id" : ObjectId("56684ee0f597654b99d0d636"),
"name" : "Scrooge",
"surname" : "McDuck",
"address" : {
"road" : "Money Bin",
"number" : 19
},
"hobbies" : [
"money",
"food",
"cooking"
]
}
{
"_id" : ObjectId("66684ee0f597654b99d0d636"),
"name" : "Mickey",
"surname" : "Mouse",
"address" : {
"road" : "Topolinia",
"number" : 34
},
"hobbies" : [
"minnie",
"cheese"
]
}
现在,如果我按数组类型查询:
Now, if I query by array type:
db.hello.find({hobbies: {$type: 4 }})
我的输出中没有任何文件.如您所见,此处 4是数组类型的数量.
I don't have any documents in output. As you can see here 4 is the number of array type.
推荐答案
这是预期的行为.您可以使用点符号" 和 $exists
运算符
This is the expected behaviour. You can simply do this using the "dot notation" and the $exists
operator
db.hello.find({ 'hobbies.0': { '$exists': true } } )
另一种方法是使用聚合和 $isArray
运算符在MongoDB 3.2中可用.但这效率较低,因为 $redact
进行了收集扫描.
Another way to do this is by using aggregation and the $isArray
operator available in MongoDB 3.2. But this is less efficient because $redact
does a collection scan.
db.hello.aggregate([
{ "$redact": {
"$cond": [
{ $isArray: "$hobbies" },
"$$KEEP",
"$$PRUNE"
]
}}
])
这篇关于按数组类型查询-MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文