Database

[{"_id":1,"parentId":null,},{"_id":2,"parentId":null,},{"_id":3,"parentId":1,},{"_id":4,"parentId":1,},{"_id":5,"parentId":2,},{"_id":6,"parentId":5,},]

Query

db.collection.aggregate([{$match:{parentId:null}},{$graphLookup:{from:"collection",startWith:"$_id",connectFromField:"_id",connectToField:"parentId",as:"descendants",depthField:"depth",},},{$unwind:"$descendants",},{$group:{_id:"$descendants.depth",count:{$sum:1,},},},{$project:{_id:0,depth:"$_id",count:"$count",},},{$sort:{depth:1,},},])

Result