I have a data structure like this in MongoDB. It can have many levels:
{
_id: ObjectId("123"),
name: "Top level",
someData: "hello world",
parent: null,
children: {
"456": {
_id: ObjectId("456"),
name: "Nested Obj",
parent: "123",
someData: "lorem ipsum",
children: {
"963": {
_id: ObjectId("963"),
name: "2nd level nesting",
parent: "456",
someData: "some data",
children: {}
}
},
"798": {
_id: ObjectId("798"),
parent: "123",
name: "Another entry",
someData: "more data here",
children: {},
}
}
}
Is there a way to make a query that would allow me to:
- Recursively apply a projection to all nested objects.
- Create a calculated field that contains the path to get to each object.
For example, say that I am only interested in the _id
and name
fields, I would expect to see this as a result of the query:
{
_id: ObjectId("123"),
name: "Top level",
path: []
children: {
"456": {
_id: ObjectId("456"),
name: "Nested Obj",
path: ["123"]
children: {
"963": {
_id: ObjectId("963"),
name: "2nd level nesting",
path: ["123", "456"]
children: {}
}
},
"798": {
_id: ObjectId("798"),
name: "Another entry",
path: ["123"]
children: {},
}
}
}