I've the following structure of documents in MongoDB. The array records contain different persons that have the roles teacher or student.
[
{_id: 1, persons: [{role:"teacher", name: "Mark", school: "", county: "Oneida"}, {role:"student", name: "John", school: "LM High School", county:""}]},
{_id: 2, persons: [{role:"teacher", name: "Robert", school: "", county: "Onondaga"}, {role:"student", name: "David", school: "Beaker High School", county:""}}]}
]
I need to get the output in the following format. From the first matching teacher person I need to select county, and from the first matching student person I need to select the school. I need to project both school and county from the nested array element level to the root document level.
[
{_id: 1, county: "Oneida", school: "LM High School"},
{_id: 2, county: "Onondaga", school: "Beaker High School"}
]
What can be the appropriate aggregation step? I tried several steps like arrayElemAt, projection, etc. but couldn't get the correct one.