Mongo Aggregate Query 获取嵌套输出

问题描述 投票:0回答:1

我正在尝试通过加入 3 个不同的集合名称 departmentelectivesstudents 来使用 mongo 聚合查询。请找到以下集合的示例数据,

部门

{
  _id : ObjectId('243s22ca4ff32423ef34'),
  departmentName : "Computer Science",
  headOfDepartment : "243s22ca4ff32423ef12"
  .
  .
  .
}

选修课

{
  _id : ObjectId('243s22ca4ff32423ef25'),
  electiveName : "Basics of OOPs",
  departmentId : "243s22ca4ff32423ef34"
  .
  .
  .
}

同学们

{
  _id : ObjectId('243s22ca4ff32423ef37'),
  studentName : "Raghu",
  electiveId : "243s22ca4ff32423ef25"
  .
  .
  .
}

我正在尝试通过应用基于部门的过滤器来构建聚合查询,以获得如下所示的示例输出,

{
  departmentName : "Computer Science",
  headOfDepartment : "243s22ca4ff32423ef12",
  electivesList : [
  {
     electiveId : "243s22ca4ff32423ef25",
     electiveName : "Basics of OOPs",
     studentsCount : 20,
     studentsList : [
     {
        studentId : "243s22ca4ff32423ef37",
        studentName : "Raghu",
     }
     ]
  }
  ]
}

我目前一直在查找第二个集合(选修课)和第三个集合(学生)。请提供一些指导。

mongodb aggregation-framework aggregate
1个回答
0
投票

你必须使用 $lookup 根级别和内部,但正如 @aneroid 所说,你的 ObjectId 无效,而且它是一个字符串,这就是为什么我将 _id 转换为字符串

[
  {
    $lookup:
      {
        from: "electives",
        let: {
          id: {
            $toString: "$_id",
          },
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: ["$departmentId", "$$id"],
              },
            },
          },
          {
            $lookup: {
              from: "students",
              let: {
                id2: {
                  $toString: "$_id",
                },
              },
              pipeline: [
                {
                  $match: {
                    $expr: {
                      $eq: [
                        "$electiveId",
                        "$$id2",
                      ],
                    },
                  },
                },
              ],
              as: "studentsList",
            },
          },
        ],
        as: "electivesList",
      },
  },
]
© www.soinside.com 2019 - 2024. All rights reserved.