Reputation: 157
This is a new requirement I need to implement in my personal project. I successfully joined two collections using aggregate (previous question). Now, I have a new collection that I need to join. Please see codes below:
Student model:
{
fullname: { type: String, required: true },
email: { type: String, required: true },
}
Exams model:
{
test: { type: String, required: false },
top10: [
type: {
studentId: { type: String, required: true },
score: { type: Number, required: false },
}
]
}
Aggregated collections:
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"
}
}
}
}
])
Now, the 3rd collection is called Teacher.
Teacher model:
{
fullName: { type: String, required: false },
studentId: { type: String, required: false }
}
Expected output should be:
{
"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"
}
]
}
Appreciate kind of help. Thanks!
Upvotes: 1
Views: 64
Reputation: 36094
You can add these 2 more pipelines before the $group pipeline,
$lookup
join collection with teacher$addFields
to get convert array to object$group
to add teacher name in students array {
$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", ""] }
}
}
}
}
Upvotes: 1