0

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

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Vishwas. The above query returns complete document. Is it possible to return the sub documents that only get matched.
@Sham332 use $ project like this find({your query criteria},{"categories.$":1}
@Sham332 please see edited answer. If you want only sub document then use {"categories.$":1} only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.