你可以试试,
-
$lookup
with students
收藏
-
$project
显示必填字段,$map
迭代top10数组的循环并在内部使用$reduce
获取学生的全名并使用以下命令与 top10 对象合并$mergeObjects
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"
]
}
}
}
}
]
}
}
}
}
}
])
操场 https://mongoplayground.net/p/_ioLktXuvgj
您可以使用的第二个选项$unwind
before $lookup
,
-
$unwind
解构top10
array
-
$lookup
with students
收藏
-
$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"
}
}
}
}
])
操场 https://mongoplayground.net/p/rUF0jNiqkJM