Database

db={"fileSystem":[{"_id":"a","label":"Root","children":["b","f"],"parent":null},{"_id":"b","label":"Nested folder 1","children":["c","d","e"],"parent":"a"},{"_id":"c","label":"Nested File 1.1","parent":"b"},{"_id":"d","label":"Nested File 1.2","parent":"b"},{"_id":"e","label":"Nested File 1.3","parent":"b"},{"_id":"f","label":"Nested folder 2","children":["g","h","i","m","n"],"parent":"a"},{"_id":"g","label":"Nested file 2.1","parent":"f"},{"_id":"h","label":"Nested file 2.2","parent":"f"},{"_id":"i","label":"Nested folder 3","children":["j","k","l"],"parent":"f"},{"_id":"j","label":"Nested file 3.1","parent":"i"},{"_id":"k","label":"Nested file 3.2","parent":"i"},{"_id":"l","label":"Nested file 3.3","parent":"i"},{"_id":"m","label":"Nested file 3.4","parent":"f"},{"_id":"n","label":"Nested folder 4","children":["o","p","q"],"parent":"f"},{"_id":"o","label":"Nested file 4.1","parent":"n"},{"_id":"p","label":"Nested file 4.2","parent":"n"},{"_id":"q","label":"Nested folder 5","children":["r","s","t"],"parent":"n"},{"_id":"r","label":"Nested file 5.1","parent":"q"},{"_id":"s","label":"Nested file 5.2","parent":"q"},{"_id":"t","label":"Nested file 5.3","parent":"q"}]}

Query

db.fileSystem.aggregate([{"$match":{"_id":"a"}},{"$graphLookup":{"from":"fileSystem","startWith":"$children","connectFromField":"children","connectToField":"_id","as":"theKids","depthField":"level"}},{"$set":{"children":{"$function":{"body":"function x(root, list) {let map = {}, node, roots = [], i = 0;const len = list.length;for (; i < len; ++i) {map[list[i]._id] = i;if (list[i].children) 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