Database
[{"id":"45TYYU","parent_id":null,"name":"account 1","type":1,"category":1},{"id":"45TYYUA","parent_id":null,"name":"account 1","type":1,"category":1},{"id":"45TYYXT","parent_id":"45TYYU","name":"account 2","type":1,"category":1},{"id":"45TYYPZ","parent_id":"45TYYU","name":"account 3","type":1,"category":1},{"id":"45TYYPZRE","parent_id":"45TYYPZ","name":"account 4","type":1,"category":1},{"id":"45TYYPZSX","parent_id":"45TYYPZ","name":"account 5","type":1,"category":1},{"id":"45TYYPZGP","parent_id":"45TYYXT","name":"account 6","type":1,"category":1}]
Query
db.collection.aggregate([{$match:{parent_id:null}},{$graphLookup:{from:"collection",startWith:"$id",connectFromField:"id",connectToField:"parent_id",depthField:"level",as:"children"}},{$unwind:{path:"$children",preserveNullAndEmptyArrays:true}},{$sort:{"children.level":-1}},{$group:{_id:"$id",parent_id:{$first:"$parent_id"},name:{$first:"$name"},type:{$first:"$type"},category:{$first:1},children:{$push:"$children"}}},{$addFields:{children:{$reduce:{input:"$children",initialValue:{level:-1,presentChild:[],prevChild:[]},in:{$let:{vars:{prev:{$cond:[{$eq:["$$value.level","$$this.level"]},"$$value.prevChild","$$value.presentChild"]},current:{$cond:[{$eq:["$$value.level","$$this.level"]},"$$value.presentChild",[]]}},in:{level:"$$this.level",prevChild:"$$prev",presentChild:{$concatArrays:["$$current",[{$mergeObjects:["$$this",{children:{$filter:{input:"$$prev",as:"e",cond:{$eq:["$$e.parent_id","$$this.id"]}}}}]}]]}}}}}}}},{$addFields:{children:"$children.presentChild"}}])