【问题标题】:MongoBb - Aggregation step to project elements from matching nested array document to root document levelMongoDb - 从匹配嵌套数组文档到根文档级别的项目元素的聚合步骤
【发布时间】: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


    【解决方案1】:
    • $filter迭代persons数组循环,分别过滤教师和学生
    • 要从数组中获取第一个元素,请使用 MongoDB 4.4 中的 $first,下面您可以使用 $arrayElemAt
    db.collection.aggregate([
      {
        $project: {
          teacher: {
            $filter: {
              input: "$persons",
              cond: { $eq: ["$$this.role", "teacher"] }
            }
          },
          student: {
            $filter: {
              input: "$persons",
              cond: { $eq: ["$$this.role", "student"] }
            }
          }
        }
      },
      {
        $project: {
          county: { $first: "$teacher.county" },
          school: { $first: "$student.school" }
        }
      }
    ])
    

    Playground

    【讨论】:

    • 谢谢!第二步 $first 对我不起作用。我不得不使用类似县的东西:{ $arrayElemAt: ["$teacher.county",0] }
    • 好的,$first 将从 mongodb v4.4 开始工作。
    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多