Database

db={"courses":[{_id:1,title:"maths",members:["p1","p2","s1","s2","s3","s4","s5"]}],"professors":[{_id:"p1",name:"Dr. Johnson"},{_id:"p2",name:"Dr. Wong"}],"students":[{_id:"s1",name:"Alice"},{_id:"s2",name:"Bob"},{_id:"s3",name:"Chuck"},{_id:"s4",name:"Dean"},{_id:"s5",name:"Eve"}]}

Query

db.professors.aggregate([{"$set":{"type":"professor"}},{"$unionWith":{"coll":"students","pipeline":[{"$set":{"type":"student"}}]}},{"$merge":{"into":"members","on":"_id"}}])

Result