Database
[{"_id":"62acec38aa7bfb93f882c7d5","attribute_ids":["62acff98aa7bfb93f882c7f2","62acff15c51e86326c759dae"],"parent_id":null,"name":"category1"},{"_id":"62acec38aa7bfb93f882c7d4","attribute_ids":["62a0cfb6ba45413ec2aea923"],"parent_id":"62acec38aa7bfb93f882c7d5","name":"category2"},{"_id":"62adcdbaaa7bfb93f882c7f8","attribute_ids":["62acff98aa7bfb93f882c7f2","62acff15c51e86326c759dae"],"parent_id":"62acec38aa7bfb93f882c7d4","name":"category2"}]
Query
db.collection.aggregate([{$graphLookup:{from:"collection",startWith:"$parent_id",connectFromField:"parent_id",connectToField:"_id",depthField:"level",as:"parent"}},{$unwind:{path:"$parent",preserveNullAndEmptyArrays:true}},{$sort:{"parent.level":-1}},{$group:{_id:"$_id",parent_id:{$first:"$parent_id"},name:{$first:"$name"},attribute_ids:{$first:"$attribute_ids"},parent:{$push:"$parent"}}},{$addFields:{parent:{$reduce:{input:"$parent",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",{parent:{$first:{$filter:{input:"$$prev",as:"e",cond:{$eq:["$$e._id","$$this.parent_id"]}}}}}]}]]}}}}}}}},{$addFields:{parent:{$first:"$parent.presentChild"}}}])