{
'a': 1,
'b':2,
'c': 3,
'd': [
{'e': 4, 'f': 5, 'g': 6},
{'e': 0, 'f': '', 'g': 3},
{'e': 1, 'f': '', 'g': 3},
]
}
{
'a': 1,
'b':2,
'c': 3,
'd': [
{'e': 4, 'f': '', 'g': 6},
{'e': 0, 'f': '', 'g': 3},
{'e': 1, 'f': '', 'g': 3},
]
}
这样的记录,问题是怎么获取d数组中f都为空的文档(如上的结果是文档2)?谢谢
大家讲道理2017-04-24 09:13:43
I only know how to implement this using $where
, I don’t know about other methods yet.
注意
——————————————————————————————Excerpted from "The Authoritative Guide to Mongodb (E2)"If it is a frequent query, it is strongly not recommended to use
is only used to further filter the results.$where
,它会遍历所有文档,每个文档都会从BSON
转换成javascript对象,然后通过表达式来处理,比常规查询慢很多,只有走投无路时才用。先使用常规查询进行过滤,然后再使用$where
,这样组合使用可以降低性能损失。如果可能先使用索引进行过滤,$where
. It will traverse all documents, and each document will be converted fromBSON
to a javascript object, and then processed through expressions, which is much slower than regular queries. , only used when desperate. Use regular queries to filter first, and then use
. This combination can reduce performance loss. If possible to filter using the index first,
🎜Code: 🎜
db.collection.find({"$where":function(){
var d = this.d, i = 0, j = d.length;
for(i,j;i<j;i++){
if(d[i].f != "")return false;
};
return true;
}});
PHP中文网2017-04-24 09:13:43
db.demo.find({d: {$not:{$elemMatch: {f: {$ne: ""}}}}})
Tested it on mongo shell:
> db.demo.insert({
... 'a': 1,
... 'b':2,
... 'c': 3,
... 'd': [
... {'e': 4, 'f': '', 'g': 6},
... {'e': 0, 'f': '', 'g': 3},
... {'e': 1, 'f': '', 'g': 3},
... ]
... } )
WriteResult({ "nInserted" : 1 })
> db.demo.insert({
... 'a': 1,
... 'b':2,
... 'c': 3,
... 'd': [
... {'e': 4, 'f': 5, 'g': 6},
... {'e': 0, 'f': '', 'g': 3},
... {'e': 1, 'f': '', 'g': 3},
... ]
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo.find({d: {$not:{$elemMatch: {f: {$ne: ""}}}}})
{ "_id" : ObjectId("54129ff745d4261bacca6dcd"), "a" : 1, "b" : 2, "c" : 3, "d" : [ { "e" : 4, "f" : "", "g" : 6 }, { "e" : 0, "f" : "", "g" : 3 }, { "e" : 1, "f" : "", "g" : 3 } ] }