Query deeply embeded documents in MongoDB with C# driver

261 views Asked by At

This is just an example code... I have managed to get to the third embeded document using .$ , but not further... How do I query the fourth nested part(article headings)?

  {
    "bookTitle": "MongoDB",
    "_id": ObjectId("530dea1d2dbf280000533b60"),
    "bookChapters": [{
    "chapterTitle": "chapterTitle",
    "_id": ObjectId("530dea1d2dbf280000533b61"),
    "chapterArticles": [{
        "articleTitle": "articleTitle",
        "_id": ObjectId("530dea1d2dbf280000533b62"),
        "articleHeadings": [{
            "headingTitle": "headingTitle",
            "_id": ObjectId("530dea1d2dbf280000533b63")
        }]
    }]
    }],
    "__v": 0
}
1

There are 1 answers

0
Vishwas On BEST ANSWER

You can use $elemMatch to match nested element in array. I used headingTitle to match here. Query will be like following-

db.collection.find({
    "bookChapters": {
    "$elemMatch": {
        "chapterArticles": {
            "$elemMatch": {
                "articleHeadings": {
                    "$elemMatch": {
                        "headingTitle": "headingTitle"
                    }
                }
            }
        }
    }
    }
})

If you want to convert it to mongo c# driver then you can refer this