UPDATE
我认为你的主要问题是随机选择amount
数量quiz
每节课下都有。自从$sample
没有帮助使用$function https://docs.mongodb.com/manual/reference/operator/aggregation/function/(MongoDB 4.4 版本中的新增功能)。
Solution
Inside $function
运算符写入一些逻辑
-
随机排列问题 https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array/6274381#6274381(您可以根据您的要求进行更改)。
- 对其进行切片以返回数字(
amount
)所需的问题。
db.lessons.aggregate([
{ $match: { "quiz.status": 1 } },
{
$lookup: {
from: "quiz",
let: { "lesson_id": "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$lesson_id", "$$lesson_id"] }
}
},
{
$project: {
title: 1,
check_list: 1,
duration: 1
}
}
],
as: "questions"
}
},
{
$project: {
quiz: {
$function: {
body: function(questions, amount) {
if (amount == 0) return [];
for (let i = questions.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[questions[i], questions[j]] = [questions[j], questions[i]];
}
return questions.slice(0, amount);
},
args: ["$questions", { $ifNull: ["$quiz.amount", 0] }],
lang: "js"
}
}
}
},
{ $unwind: "$quiz" },
{ $replaceRoot: { newRoot: "$quiz" } }
]);
$sample
不支持变量。必须明确指定一个数字,例如:
{
$sample: { size: 1 }
}
还要更换你的let
如下图,因为最后lesson
文档没有amount
提交于quiz
object
let: {
'lesson_id': '$_id',
'limit': { $ifNull: ['$quiz.amount', 0] } // or any other number.
},
Wrong:
{
$sample: { size: "$$limit" } // Wont work!
}