[英]Mongoose join two collections and get only specific fields from the joined collection
我在 mongoose 中加入兩個集合時遇到問題。 我有兩個集合,即:學生和考試。
學生模型:
{
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 },
}
]
}
現在,我想通過studentId加入他們兩個。 結果應該是:
{
"test": "Sample Test #1",
"students": [
{
"studentId": "5f22ef443f17d8235332bbbe",
"fullname": "John Smith",
"score": 11
},
{
"studentId": "5f281ad0838c6885856b6c01",
"fullname": "Erlanie Jones",
"score": 9
},
{
"studentId": "5f64add93dc79c0d534a51d0",
"fullname": "Krishna Kumar",
"score": 5
}
]
}
我所做的是使用聚合:
return await Exams.aggregate([
{$lookup:
{
from: 'students',
localField: 'top10.studentId',
foreignField: '_id',
as: 'students'
}
}
]);
但這個結果並不是我所希望的。 任何想法如何實現這一目標? 我很樂意提供任何幫助。 謝謝!
你可以試試,
$lookup
與students
集合$project
顯示必填字段, $map
迭代top10 數組的循環,在內部使用$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"
]
}
}
}
}
]
}
}
}
}
}
])
您可以在$lookup
之前使用$unwind
第二個選項,
$unwind
解構top10
數組$lookup
與students
集合$addFields
使用$arrayElemtAt
將學生數組轉換為對象$group
by _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"
}
}
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.