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:{$arrayToObject:{$map:{input:{$objectToArray:"$children"},as:"c",in:{$let:{vars:{path:["$$c.v.parent"]},in:{k:"$$c.k",v:{_id:"$$c.v._id",name:"$$c.v.name",path:"$$path",children:{/** copy-paste this full { ... } object* as value of `children: {}` below*/$arrayToObject:{$map:{input:{$objectToArray:"$$c.v.children"},as:"c",in:{$let:{vars:{path:{$concatArrays:["$$path",["$$c.v.parent"]]}},in:{k:"$$c.k",v:{_id:"$$c.v._id",name:"$$c.v.name",path:"$$path",/** replace the `{}` value below*/children:{/** copy-paste this full { ... } object* as value of `children: {}` below*/$arrayToObject:{$map:{input:{$objectToArray:"$$c.v.children"},as:"c",in:{$let:{vars:{path:{$concatArrays:["$$path",["$$c.v.parent"]]}},in:{k:"$$c.k",v:{_id:"$$c.v._id",name:"$$c.v.name",path:"$$path",/** replace the `{}` value below*/children:{/** copy-paste this full { ... } object* as value of `children: {}` below*/$arrayToObject:{$map:{input:{$objectToArray:"$$c.v.children"},as:"c",in:{$let:{vars:{path:{$concatArrays:["$$path",["$$c.v.parent"]]}},in:{k:"$$c.k",v:{_id:"$$c.v._id",name:"$$c.v.name",path:"$$path",/** replace the `{}` value below*/children:{/** copy-paste this full { ... } object* as value of `children: {}` below*/$arrayToObject:{$map:{input:{$objectToArray:"$$c.v.children"},as:"c",in:{$let:{vars:{path:{$concatArrays:["$$path",["$$c.v.parent"]]}},in:{k:"$$c.k",v:{_id:"$$c.v._id",name:"$$c.v.name",path:"$$path",/** replace the `{}` value below*/children:{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}})