Node.js Mongoose将附加集合连接到两个聚合集合
这是我需要在我的个人项目中实现的新要求。我使用聚合成功加入了两个集合。现在,我需要加入一个新集合。请参阅下面的代码: 学生模型:Node.js Mongoose将附加集合连接到两个聚合集合,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,这是我需要在我的个人项目中实现的新要求。我使用聚合成功加入了两个集合。现在,我需要加入一个新集合。请参阅下面的代码: 学生模型: { fullname: { type: String, required: true }, email: { type: String, required: true }, } 考试模式: { test: { type: String, required: false }, top10: [ type: { studentId:
{
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"
}
}
}
}
])
现在,第三个集合称为教师
教师模式:
{
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"
}
]
}
感谢您的帮助。谢谢!您可以在$group管道之前再添加这两个管道
与教师加入集合$lookup
获取转换数组到对象$addFields
在学生数组中添加教师姓名$group
谢谢你的帮助!我从你那里学到了一些东西。另一个问题。如果学生没有老师,我们该如何处理?我想为此显示空字符串。我已使用$ifNull运算符进行了更新,因为如果不是fount,它将返回null。谢谢@turivishal.Btw,是否可以在对象而不是数组中显示结果集?添加两个在$unwind students和$replaceWith students末尾的新管道您需要在查询后执行此操作,以便从零位置访问对象。例如
let response=wait aggregate();console.log(response[0])
{
$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", ""] }
}
}
}
}