試すことができます
-
$lookupstudentsと コレクション -
$project必須フィールドを表示するには、$maptop10配列のループを繰り返し、内部で$reduceを使用します 学生からフルネームを取得し、$mergeObjectsを使用してtop10オブジェクトとマージします
db.exams.aggregate([
{
$lookup: {
from: "students",
localField: "top10.studentId",
foreignField: "_id",
as: "students"
}
},
{
$project: {
test: 1,
students: {
$map: {
input: "$top10",
as: "top10",
in: {
$mergeObjects: [
"$$top10",
{
fullname: {
$reduce: {
input: "$students",
initialValue: 0,
in: {
$cond: [
{ $eq: ["$$this._id", "$$top10.studentId"] },
"$$this.fullname",
"$$value"
]
}
}
}
}
]
}
}
}
}
}
])
$unwindを使用できる2番目のオプション $lookupの前 、
-
$unwindtop10を分解します 配列 -
$lookupstudentsと コレクション -
$addFields$arrayElemtAtを使用して、学生の配列をオブジェクトに変換します -
$group_idで、学生の配列を作成し、必要なフィールドをプッシュします
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"
}
}
}
}
])