【发布时间】:2021-03-19 17:34:18
【问题描述】:
我很难理解聚合。我要做的是从一个集合中查找所有记录,然后查找另一个集合并对其进行一些计算,然后返回所有合并的响应。
考试架构
const examSchema = new mongoose.Schema({
examName: {
type: String,
trim: true,
required: [true, "Exam name is missing"],
maxlength: [60, "Max exam name length is 60 characters"],
},
duration: {
type: Number,
trim: true,
default: 0,
min: [0, "Minimum exam duration is zero minutes"],
},
}, {
timestamps: true,
});
module.exports = mongoose.model("Exam", examSchema);
问题架构
const questionSchema = new mongoose.Schema({
_refExamId: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Exam",
}],
title: {
type: String,
trim: true,
required: [true, "Question is missing"],
},
positiveMarks: {
type: Number,
required: [true, "Marks for the question is missing"],
default: 0,
},
}, {
timestamps: true,
});
module.exports = mongoose.model("Question", questionSchema);
_refExamId 这里是一个数组,因为一个问题可能会在多个考试中使用。
所以,我想要查询 exams 集合并获取所有考试及其相关问题以及每门考试的总分。
期望的输出
{
exam_name: "Demo exam 1",
total_time: 30,
total_marks: 50,
questions: [{ title: "Question 1" }, { title: "Question 2" }]
},
{
exam_name: "Demo exam 2",
total_time: 0,
total_marks: 0,
questions: []
}
.
.
.
我做了什么
const exams = await examModel.aggregate([
{
$lookup: {
from: "questions",
localField: "_id",
foreignField: "_refExamId",
as: "questions"
},
}
]);
console.log(exams);
【问题讨论】:
标签: javascript mongodb mongoose aggregation-framework