查询Mongodb中集合的子文档中的子文档

时间:2015-06-24 13:12:46

标签: mongodb

我的收藏名称如下公司。

我想查询对应于C1S1category1的网址。我不知道它属于哪个companyName以及它属于哪个catergories。

请您告诉我在Mongoshell中需要使用哪些查询来查询catergoryname为C1S1category1的文档

{"companyName": "C1",
"url": "www.com1",
"categories" : [
        {"SlNo" : 1,
        "url" : "www.com1",
        "subcategories" : [
            {
            "CatergoryName":"C1S1category1",
            "Url" : "www.com3"
            },
            {
            "CatergoryName":"C1S1category2",
            "Url" : "www.com3"
            }
            ]
         },
       {
       "SlNo" : 2,
        "url" : "www.com1",
        "subcategories" : [
            {
            "CatergoryName":"C1S2category1",
            "Url" : "www.com3"
            },
            {
            "CatergoryName":"C1S2category2",
            "Url" : "www.com3"
            }
            ]
        }   
    ]
},
{"companyName": "C2",
"url": "www.com21",
"categories" : [
        {"SlNo" : 1,
        "url" : "www.com22",
        "subcategories" : [
            {
            "CatergoryName":"C2S1category1",
            "Url" : "www.com23"
            },
            {
            "CatergoryName":"C2S1category2",
            "Url" : "www.com23"
            }
            ]
         },
       {
       "SlNo" : 2,
        "url" : "www.com1",
        "subcategories" : [
            {
            "CatergoryName":"C2S2category1",
            "Url" : "www.com23"
            },
            {
            "CatergoryName":"C2S2category2",
            "Url" : "www.com23"
            }
            ]
        }   
    ]
}

1 个答案:

答案 0 :(得分:1)

您需要使用$elemMatch获取所需的输出,如下所示:

db.collection.find({
    "categories": {
    $elemMatch: {
        subcategories: {
            $elemMatch: {
                CatergoryName: "C1S1category1"
            }
        }
    }
    }
},{"categories.$":1,"companyName":1,"url":1}).pretty()