Database
db={"administrative_divisions":[{"_id":1,"name":"New York State","pid":0,"level":1,"sort":2.00223000,"leaf":false,"path":"1"},{"_id":2,"name":"New York City","pid":1,"level":2,"sort":2.0000000,"leaf":false,"path":"1, 2"},{"_id":4,"name":"The Bronx","pid":2,"level":3,"sort":1.0000000,"leaf":true,"path":"1, 2, 4"},{"_id":5,"name":"Brooklyn","pid":2,"level":3,"sort":4.0000000,"leaf":true,"path":"1, 2, 5"},{"_id":6,"name":"Manhattan","pid":2,"level":3,"sort":5.0000000,"leaf":true,"path":"1, 2, 6"},{"_id":7,"name":"Queens","pid":2,"level":3,"sort":6.0000000,"leaf":true,"path":"1, 2, 7"},{"_id":8,"name":"Staten Island","pid":2,"level":3,"sort":12.0002220,"leaf":true,"path":"1, 2, 8"},{"_id":3,"name":"Albany","pid":1,"level":2,"sort":1.0023400,"leaf":true,"path":"1, 3"}]}
Query
db.administrative_divisions.aggregate([{"$match":{pid:0}},{$graphLookup:{from:"administrative_divisions",startWith:"$_id",connectFromField:"_id",connectToField:"pid",depthField:"level",as:"children"}},{$unwind:{path:"$children",preserveNullAndEmptyArrays:true}},{$sort:{"children.level":-1,"children.sort":1}},{$group:{_id:"$_id",name:{$first:"$name"},path:{$first:"$path"},pid:{$first:"$pid"},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.pid","$$this._id"]}}}}]}]]}}}}}}}},{$addFields:{children:"$children.presentChild"}}])