Database
[{"collection":"Company","count":5,"content":{"_id":{"type":"reference","id":0,"refContent":{"type":"autoincrement","autoType":"int"}},"name":{"type":"faker","method":"Company"}}},{"collection":"Department","count":30,"content":{"_id":{"type":"reference","id":1,"refContent":{"type":"autoincrement","autoType":"int"}},"name":{"type":"enum","values":["Management","Marketing","Investor Relations","Engineering","Manufacturering","Security","IT","HR","Facilities","Accounting"]},"company_id":{"type":"ref","id":0}}},{"collection":"Person","count":100,"content":{"_id":{"type":"autoincrement","autoType":"int"},"name":{"type":"faker","method":"Name"},"department_id":{"type":"ref","id":1}}}]
Query
db.Company.aggregate([{/** get all company departments*/"$lookup":{"from":"Department","localField":"_id","foreignField":"company_id","as":"departments","pipeline":[{/** get all persons in department*/"$lookup":{"from":"Person","localField":"_id","foreignField":"department_id","as":"persons"}}]}},{"$project":{"_id":0,"name":1,"persons":{/** concat all department persons*/"$reduce":{"input":"$departments","initialValue":[],"in":{"$concatArrays":["$$value","$$this.persons"]}}}}}])