如何从mongodb获得匹配的子文档?

时间:2014-11-08 07:17:31

标签: python mongodb mongodb-query aggregation-framework

我有一个像这样的集合

{
    "_id" : ObjectId("545dad3562fa028fb48832f0"),
    "key" : "123456",
    "members" : [
            {
                    "name" : "Shiva",
                    "country" : "India",
                    "profession" : "Software"
            },
            {
                    "name" : "Neil",
                    "country" : "Australia",
                    "profession" : "Software"
            },
            {
                    "name" : "anil",
                    "country" : "India",
                    "profession" : "Software"
            }

    ]
}

现在我想要检索国家印度的记录。 当我尝试这样的时候

db.user_details.find({ 'key' :'123456','members':{$elemMatch:{'country': "India"}}}, {'members.$': 1}).pretty()

当执行上面的代码时,我只是第一次出现,如何从该文档中获取所有匹配的子文档(如name:Shivaname:Anil

1 个答案:

答案 0 :(得分:3)

对应$elemMatch运算符的positional $运算符目前仅与符合指定条件的第一元素匹配。

为了获得“多个”匹配,最好的方法是使用聚合框架:

 db.user_details.aggregate([
     # Always match first to at least find the "documents" with matching elements
     { "$match": {
         "members.country": "India"
     }},

     # Use $unwind to "de-normalize" the array as individual documents
     { "$unwind": "$members" },

     # Then match again to "filter" the content down to matches
     { "$match": {
         "members.country": "India"
     }},

     # Group back to keep an array
     { "$group": {
         "_id": "$_id",
         "key": { "$first": "$key" },
         "members": { "$push": "$members" }
     }}
 ])

这是从数组中“过滤”多个匹配的基本过程。基本投影目前无法做到。

返回此内容:

{
    "_id" : ObjectId("545dad3562fa028fb48832f0"),
    "key" : "123456",
    "members" : [
            {
                    "name" : "Shiva",
                    "country" : "India",
                    "profession" : "Software"
            },
            {
                    "name" : "anil",
                    "country" : "India",
                    "profession" : "Software"
            }
    ]
}