我必须按类型查询我的mongoDB集合 .
假设我有 hello 集合的这两个文件:
{
"_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"
]
}
现在,如果我按数组类型查询:
db.hello.find({hobbies: {$type: 4 }})
我输出中没有任何文件 . 如您所见here 4是数组类型的数量 .
4 回答
这是预期的行为 . 您可以使用"dot notation"和$exists运算符来执行此操作
另一种方法是使用聚合和MongoDB 3.2中提供的$isArray运算符 . 但这效率较低,因为$redact进行了集合扫描 .
根据the docs,您需要使用where子句:
您需要使用
where
子句 . 请参考以下语法:db.hello.find( { $where : "Array.isArray(this.hobbies)" } );
看https://docs.mongodb.org/v3.0/reference/operator/query/type/#arrays
当您在
hobbies
字段上查询时,查询将实际尝试匹配字段内的元素,因为它是一个数组 . 所以你可以这样做:但它不会非常有效,也不会使用索引 .