【发布时间】:2021-06-06 15:40:30
【问题描述】:
我在 MongoDB 中有以下文档结构。数组记录包含具有教师或学生角色的不同人员。
[
{_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:""}}]}
]
我需要得到以下格式的输出。从第一个匹配的教师中我需要选择县,从第一个匹配的学生中我需要选择学校。我需要将学校和县从嵌套数组元素级别投影到根文档级别。
[
{_id: 1, county: "Oneida", school: "LM High School"},
{_id: 2, county: "Onondaga", school: "Beaker High School"}
]
什么是合适的聚合步骤?我尝试了几个步骤,如 arrayElemAt、投影等,但没有得到正确的。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework