Question

How to get sub documents value from following BSON Document

{
"_id" : ObjectId("52415e45ccf279207b91a2a0"),
"created" : ISODate("2013-09-24T09:41:25.760Z"),
"creator" : "52415e45ccf279207b91a29e",
"description" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"lastModif" : ISODate("2013-09-24T09:41:25.760Z"),
"title" : "My post title",
"comments" : [ 
    {
        "title" : "Comment 1",
        "content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        "created" : ISODate("2013-09-24T09:41:25.764Z"),
        "lastModif" : ISODate("2013-09-24T09:41:25.764Z"),
        "creator" : "52415e45ccf279207b91a2a3",
        "_id" : ObjectId("52415e45ccf279207b91a2a1")
    },
    {
        "title" : "Comment 2",
        "content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        "created" : ISODate("2013-09-24T09:41:25.764Z"),
        "lastModif" : ISODate("2013-09-24T09:41:25.764Z"),
        "creator" : "52415e45ccf279207b91a2a3",
        "_id" : ObjectId("52415e45ccf279207b91a29f")
    },
    {
        "title" : "Comment 3",
        "content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        "created" : ISODate("2013-09-24T09:41:25.764Z"),
        "lastModif" : ISODate("2013-09-24T09:41:25.764Z"),
        "creator" : "52415e45ccf279207b91a2a3",
        "_id" : ObjectId("52415e45ccf279207b91a287")
    }
... 
  ]
}

I need to get the sub document of where title='Comment 1'.

Can any one help me.

Was it helpful?

Solution

If you want to find documents that has a comment with title = "Comment 1" then you can use :

db.test.find({"comments.title" : "Comment 1"})

If you also want to project result so that it only shows subdocument, then you should update query as follows :

db.test.find({"comments.title" : "Comment 1"},{comments : {$elemMatch : {title:"Comment 1"}}})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top