cynical biscuit
cynical biscuit

Reputation: 353

Finding Sub-documents through dot notation in mongodb

I have a simplified collection structure below for simplicity's sake. I am unable to query the specific sub-documents under the profile field.

For example, I want to find the sub-document "profiles.Bernie". Is there a find() query that will allow me to only retrieve the document for Bernie (i.e. category and id for Bernie)? Apologies if this is a duplicate, but I was unable to find solutions that catered the way this collection is structured below

{
        "_id" : ObjectId("56aec822ceb6e9dc23d32271"),
        "sm_user" : "user1",
        "profiles" : {
                "Bernie" : {
                        "category" : "Politics",
                        "id" : "bernie"
                },
                "Hilary" : {
                        "category" : "Politics",
                        "id" : "hilary"
                }
        }
}

Upvotes: 0

Views: 569

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

Yes, you can choose to just get the Bernie subtree and suppress the normally included _id;

db.test.find({},{ _id:0, "profiles.Bernie":1 })

This will include the structure leading up to Bernie (aka the profiles tag), but only the data from that subtree.

If you don't want the structure to remain, you could also use the aggregate framework to project Bernie to the root of the output document;

db.test.aggregate([{$project: { _id:0, 'Bernie': "$profiles.Bernie"}}])

Upvotes: 1

Related Questions