Shambu
Shambu

Reputation: 2832

Querying subdocument inside a subdocument of a collection in Mongodb

I have the collection named companies as below.

I want to query the url corresponding to C1S1category1 . I do not know which companyName it belongs and which catergories it belongs to.

Please can you let me know what query I need to use in Mongoshell to query the document having catergoryname as 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"
            }
            ]
        }   
    ]
}

Upvotes: 0

Views: 146

Answers (1)

Vishwas
Vishwas

Reputation: 7067

You need to use $elemMatch to get required output as following:

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

Upvotes: 1

Related Questions