Database
db={"categories":[{"_id":1,"name":"A"},{"_id":2,"name":"B","categoryId":1},{"_id":3,"name":"C","categoryId":1},{"_id":4,"name":"D","categoryId":2},{"_id":5,"name":"E","categoryId":3},{"_id":6,"name":"F","categoryId":2}],"locos":[{"_id":1,"name":"X","categoryId":2},{"_id":2,"name":"Y","categoryId":3},{"_id":3,"name":"B","categoryId":1}]}
Query
db.categories.aggregate([{"$match":{_id:1}},{"$graphLookup":{"from":"categories","startWith":"$_id","connectFromField":"_id","connectToField":"categoryId","as":"categoryLookup"}},{"$graphLookup":{"from":"locos","startWith":"$_id","connectFromField":"_id","connectToField":"categoryId","as":"locosLookup"}},{"$project":{children:{categories:{"$map":{"input":"$categoryLookup","as":"c","in":"$$c._id"}},locos:{"$map":{"input":"$locosLookup","as":"l","in":"$$l._id"}}}}}])