猫鼬将其他集合添加到两个聚合集合中

时间:2020-10-13 14:15:44

标签: node.js mongodb mongoose

这是我需要在个人项目中实现的新要求。我已成功使用聚合(previous question)加入了两个集合。现在,我需要加入一个新集合。请参见下面的代码:

学生模型:

{
  fullname: { type: String, required: true },
  email: { type: String, required: true },
}

考试模式:

{
  test: { type: String, required: false },
  top10: [
    type: {
      studentId: { type: String, required: true },
      score: { type: Number, required: false },
    }
  ]
}

汇总集合:

db.exams.aggregate([
{ $unwind: "$top10" },
{
$lookup: {
  from: "students",
  localField: "top10.studentId",
  foreignField: "_id",
  as: "students"
}
},
{ $addFields: { students: { $arrayElemAt: ["$students", 0] } } },
{
$group: {
  _id: "$_id",
  test: { $first: "$test" },
  students: {
    $push: {
      studentId: "$top10.studentId",
      score: "$top10.score",
      fullname: "$students.fullname"
    }
  }
}
}
])

现在,第三个收藏集称为 Teacher (老师)。

教师模型:

{
  fullName: { type: String, required: false },
  studentId: { type: String, required: false }
}

预期输出应为:

{
 "test": "Sample Test #1",
 "students": [
        {
            "studentId": "5f22ef443f17d8235332bbbe",
            "fullname": "John Smith",
            "score": 11,
            "teacher": "Dr. Hofstadter"
            
        },
        {
            "studentId": "5f281ad0838c6885856b6c01",
            "fullname": "Erlanie Jones",
            "score": 9,
            "teacher": "Mr. Roberts"
        },
        {
            "studentId": "5f64add93dc79c0d534a51d0",
            "fullname": "Krishna Kumar",
            "score": 5,
            "teacher": "Ms. Jamestown"
        }
    ]
}

一种帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在$ group管道之前添加另外2个管道,

  • $lookup与老师一起加入收藏集
  • $addFields将数组转换为对象
  • $group在学生数组中添加老师姓名
  {
    $lookup: {
      from: "teacher",
      localField: "top10.studentId",
      foreignField: "studentId",
      as: "students.teacher"
    }
  },
  {
    $addFields: {
      "students.teacher": { $arrayElemAt: ["$students.teacher", 0] }
    }
  },
  {
    $group: {
      _id: "$_id",
      test: { $first: "$test" },
      students: {
        $push: {
          studentId: "$top10.studentId",
          score: "$top10.score",
          fullname: "$students.fullname",
          teacher: { $ifNull: ["$students.teacher.fullname", ""] }
        }
      }
    }
  }

Playground