首页 > mongodb数组查询

mongodb数组查询

{
    '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)?谢谢


  只知道这个用$where怎么实现,其他方法我也暂时不知道。

注意

如果是经常性的查询,强烈不建议使用$where,它会遍历所有文档,每个文档都会从BSON转换成javascript对象,然后通过表达式来处理,比常规查询慢很多,只有走投无路时才用。先使用常规查询进行过滤,然后再使用$where,这样组合使用可以降低性能损失。如果可能先使用索引进行过滤,$where只用于对结果进行进一步过滤。
——————————————————————————————摘自《Mongodb权威指南(E2)》

代码:

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: ""}}}}})

在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 } ] }
【热门文章】
【热门文章】