Database

db={"catTree":[{"_id":"a","label":"Cat","children":["b","f"],"parent":null},{"_id":"b","label":"Panthera","children":["c","d","e"],"parent":"a"},{"_id":"c","label":"Lion","children":[],"parent":"b"},{"_id":"d","label":"Jaguar","children":[],"parent":"b"},{"_id":"e","label":"Tiger","children":[],"parent":"b"},{"_id":"f","label":"Small cats","children":["g","h","i","m","n"],"parent":"a"},{"_id":"g","label":"Bay cat","children":[],"parent":"f"},{"_id":"h","label":"Desert lynx","children":[],"parent":"f"},{"_id":"i","label":"Leopardus","children":["j","k","l"],"parent":"f"},{"_id":"j","label":"Guina","children":[],"parent":"i"},{"_id":"k","label":"Tigrillo","children":[],"parent":"i"},{"_id":"l","label":"Ocelot","children":[],"parent":"i"},{"_id":"m","label":"Lynx","children":[],"parent":"f"},{"_id":"n","label":"Felis","children":["o","p","q"],"parent":"f"},{"_id":"o","label":"Jungle cat","children":[],"parent":"n"},{"_id":"p","label":"Sand cat","children":[],"parent":"n"},{"_id":"q","label":"Wildcat","children":["r","s","t"],"parent":"n"},{"_id":"r","label":"African wildcat","children":[],"parent":"q"},{"_id":"s","label":"European wildcat","children":[],"parent":"q"},{"_id":"t","label":"Domestic cat","children":[],"parent":"q"}]}

Query

db.catTree.aggregate([{"$match":{"_id":"a"}},{"$graphLookup":{"from":"catTree","startWith":"$children","connectFromField":"children","connectToField":"_id","as":"theKids","depthField":"level"}},{"$set":{"children":{"$function":{"body":"function(root, list) {let map = {}, node, roots = [], i;for (i = 0; i < list.length; i += 1) {map[list[i]._id] = i;list[i].children = [];node = list[i];if (node.parent !== root) {list[map[node.parent]].children.push(node);} else {roots.push(node);}}return roots}","args":["$_id",{"$sortArray":{"input":"$theKids","sortBy":{"level":1}}}],"lang":"js"}}}},{"$unset":"theKids"}])

Result