简体   繁体   English

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

[英]How to get matched sub documents from mongodb?

I have a collection like this 我有这样的集合

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

    ]
}

Now i want to retrieve the records with country India. 现在我想用国家印度检索记录。 When i tried like this 当我尝试这样的时候

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

When executed the above code i am getting only first occurrence, How to get all the matched sub documents(like name:Shiva and name:Anil ) from that document 执行上面的代码时,我只是第一次出现,如何从该文档获取所有匹配的子文档(如name:Shivaname:Anil

The $elemMatch operator along the the counterpart positional $ operator will only currently match the first element that meets the conditions specified. 对应位置$运算符上的$elemMatch运算符目前仅匹配满足指定条件的第一个元素。

In order to get "more than one" match, the best method is to use the aggregation framework: 为了获得“多个”匹配,最好的方法是使用聚合框架:

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

That is the basic process for "filtering" more than one match from an array. 这是从数组中“过滤”多个匹配的基本过程。 The basic projection cannot currently do it. 基本投影目前无法做到。

Which returns this: 哪个返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM