Node.js Mongoose联接两个集合,并仅从联接的集合中获取特定字段
我在mongoose中加入两个集合时遇到问题。我有两个收藏,即:学生和考试 学生模型:Node.js Mongoose联接两个集合,并仅从联接的集合中获取特定字段,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在mongoose中加入两个集合时遇到问题。我有两个收藏,即:学生和考试 学生模型: { fullname: { type: String, required: true }, email: { type: String, required: true }, } 考试模式: { test: { type: String, required: false }, top10: [ type: { studentId: { type: String, requi
{
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
集合学生
显示必填字段,$project
迭代top10数组的循环,内部使用$map
从学生处获取全名,并使用$reduce
与top10对象合并$mergeObjects
第二个选项可以在
$lookup
之前使用$unwind
解构$unwind
数组top10
与$lookup
集合学生
使用$addFields
$arrayelemt
by\u id,构建学生数组并推送必填字段$group
与$lookup
集合学生
显示必填字段,$project
迭代top10数组的循环,内部使用$map
从学生处获取全名,并使用$reduce
与top10对象合并$mergeObjects
第二个选项可以在
$lookup
之前使用$unwind
解构$unwind
数组top10
与$lookup
集合学生
使用$addFields
$arrayelemt
by\u id,构建学生数组并推送必填字段$group
顺便问一下,我是否可以在现有的聚合语句中添加另一个集合?您可以使用lookup加入。我不确定,但您的架构结构和populate()不可能。好的,谢谢!顺便说一句,我这里有一个新问题:希望你能帮我。顺便说一句,我是否可以在现有的聚合语句中添加另一个集合?你可以,使用查找加入。我不确定,但使用你的架构结构和填充()是不可能的。好的,谢谢!顺便说一句,我这里有一个新问题:希望你能帮我。
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"
]
}
}
}
}
]
}
}
}
}
}
])
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"
}
}
}
}
])