Shredderroy
Shredderroy

Reputation: 2920

How can I traverse a nested document in MongoDB and return the sub-tree?

I have a document with the following structure in MongoDB:

{
    "k1": {
        "k11": {<extended-sub-document-11>},
        "k12": {<extended-sub-document-12>}
    },
    "k2": {
        "k21": {<extended-sub-document-21>}
    }
}

How can I fetch the entire object at k12? The find mechanism requires me to provide a value against which to match. But here, I simply want to traverse the path k1/k12 and retrieve the entire sub-document at that key.

Thanks in advance.

Upvotes: 1

Views: 313

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

Using projection in .find() you can try as like below :

db.collection.find({}, { "k1.k12": 1})

Test : mongoplayground

Note : You would only get values/object of k12 but as it's nested in k1, In the output you would see same structure with just k12 object in k1 like : {k1: {k12: {...}}}.

Using aggregation's $project stage :

db.collection.aggregate([ { $project: {_id :0,  k12: "$k1.k12" } } ])

Test : mongoplayground

By using aggregation $project which is way more powerful than projection in .find() you can assign a field's value to a field. In the above query we're assigning value at k1.k12 to a field k12 using $ (Which helps to get value of referenced field).

Upvotes: 1

Related Questions