Database
[{_id:"123",name:"Top level",someData:"hello world",parent:null,children:{"456":{_id:"456",name:"Nested Obj",parent:"123",someData:"lorem ipsum",children:{"963":{_id:"963",name:"2nd level nesting",parent:"456",someData:"some data",children:{"333":{_id:"333",name:"3rd level nesting",parent:"963",someData:"some data",children:{"4444":{_id:"4444",name:"4th level nesting",parent:"333",someData:"some data",children:{"55555":{_id:"55555",name:"5th level nesting",parent:"4444",someData:"some data",children:{}}}}}}}}}},"798":{_id:"798",parent:"123",name:"Another entry",someData:"more data here",children:{}}}}]
Query
db.collection.aggregate({$set:{children:{$function:{body:"function (childrenObj) { function processChildren(children, path) { for (const key in children) { if (children.hasOwnProperty(key)) { const child = children[key]; child.path = [...path]; if (child.children) { const nextPath = [...path, child._id]; processChildren(child.children, nextPath); } } } } for (const key in childrenObj) { if (childrenObj.hasOwnProperty(key)) { const parent = childrenObj[key]; if (parent && parent.children) { processChildren(parent.children, [parent._id]); } } } return childrenObj; }",args:["$children"],lang:"js"}}}})