0

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

1 Answer 1

1

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

1 Comment

That's perfect, I was having a brain fart. I forgot about the projection parameters. Thanks so much!

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.