我有3个馆藏:类别,考试和成绩。
对于每个类别,我都有一些考试。如果完成一项考试,我会将其结果添加到“结果”集合中。
我已参加每个类别的所有考试。问题是我无法数出完成了多少。
这就是我现在得到的:
{ category: "Test", total_exams: 10 }
这就是我要的:
{ category: "Test", total_exams: 10, done_exam: 4 }
在下面您可以看到我到目前为止所做的事情:
快速修复:
$lookup
阶段中,让通过examsCount._id
,$match
阶段匹配表达式中,$exam_id with $$examId
user_id
匹配条件放在表达式之外$count
文件总数 count
to get
doneExams.count this will return count in zero index, get it using
$ first or
$ arrayElemAt`db.categories.aggregate([
{
$lookup: {
from: "exams",
localField: "_id",
foreignField: "categoryId",
as: "examsCount"
}
},
{
$lookup: {
from: "results",
let: { examId: "$examsCount._id" },
pipeline: [
{
$match: {
$expr: {
$and: [{ $in: ["$exam_id", "$$examId"] }]
},
user_id: 22222222
}
},
{ $count: "count" }
],
as: "doneExams"
}
},
{
$addFields: {
examsCount: { $size: "$examsCount" },
doneExams: { $first: "$doneExams.count" }
}
}
])
有很多方法可以得到此结果,我刚刚解决了您的方法中的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句