mongodb数组查询
伊谢尔伦
伊谢尔伦 2017-04-24 09:11:43
0
2
504
{
    '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)?谢谢

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
大家讲道理

 I only know how to implement this using $where, I don’t know about other methods yet.

注意

If it is a frequent query, it is strongly not recommended to use $where,它会遍历所有文档,每个文档都会从BSON转换成javascript对象,然后通过表达式来处理,比常规查询慢很多,只有走投无路时才用。先使用常规查询进行过滤,然后再使用$where,这样组合使用可以降低性能损失。如果可能先使用索引进行过滤,$where. It will traverse all documents, and each document will be converted from BSON 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,

is only used to further filter the results.
——————————————————————————————Excerpted from "The Authoritative Guide to Mongodb (E2)"

🎜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;
}});
洪涛
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 } ] }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template