我有這個架構結構
const QuizQuestionSchema = new Schema({
course: { type: String, required: true, trim: true },
point: { type: Number, required: true, trim: true, min: 1, max: 20 },
question: { type: String, required: true, trim: true },
codeBoard: { type: String, default: null, nullable: true },
answers: { type: [String], required: true, trim: true },
correctAnswer: { type: String, required: true, trim: true }
});
從客戶端我得到檔案的陣列 id 和選定的答案[{id, answer}...]。我需要找出用戶收集了多少分,如果匹配添加分數,將正確答案與答案進行比較。這怎么能用聚合來完成?
例子
客戶
[
{ id: "61bc09994da5e9ffe47fccb9", answer: "1 2 4 3 5" },
{ id: "61bc0af14da5e9ffe47fccbb", answer: "1 4 3 2" },
...
];
服務器檔案
{
_id: new ObjectId("61bc09994da5e9ffe47fccb9"),
course: 'JavaScript',
point: 10,
question: 'What will we see in the console ?',
codeBoard: '...',
answers: [ '1 2 4 3 5', '1 5 4 3 2', '2 1 4 3 5', '1 5 3 4 2' ],
correctAnswer: '2 1 4 3 5',
__v: 0
},
{
_id: new ObjectId("61bc0af14da5e9ffe47fccbb"),
course: 'JavaScript',
point: 10,
question: 'What will we see in the console ?',
codeBoard: '...',
answers: [ '1 4 3 2', '1 2 4 3', '1 2 3 4', '1 4 2 3' ],
correctAnswer: '1 4 3 2',
__v: 0
}
uj5u.com熱心網友回復:
如果客戶端發送帶有所選答案的字串中的每個問題 id,您應該將該陣列映射到:
{
id: new ObjectId("61bc09994da5e9ffe47fccb9"),
correctAnswer: "2 1 4 3 5"
}
記住用以下方法定義 ObjectId:
const ObjectId = require('mongoose').Types.ObjectId;
然后在$or運算子中添加完整陣列,最后將每個匹配添加點分組。
db.collection.aggregate({
"$match": {
$or: [
{
id: new ObjectId("61bc09994da5e9ffe47fccb9"),
correctAnswer: "2 1 4 3 5"
},
{
id: new ObjectId("61bc0af14da5e9ffe47fccbb"),
correctAnswer: "1 4 3 2"
},
. . .
]
}
},
{
"$group": {
"_id": null, // This means that every document is grouped, because there is no condition to group by
"points": {
$sum: "$point"
}
}
})
uj5u.com熱心網友回復:
您可以使用非常直接的管道來實作這一點$lookup,如下所示:
db.users.aggregate([
{
$match: {
user_id: 1
}
},
{
"$lookup": {
"from": "quiz",
let: {
quizId: "$id",
userAnswer: "$answer"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$$quizId",
"$_id"
]
},
{
$eq: [
"$$userAnswer",
"$correctAnswer"
]
}
]
}
}
}
],
"as": "matched"
}
},
{
$group: {
_id: null,
total: {
$sum: 1
},
correct: {
$sum: {
$size: "$matched"
}
}
}
}
])
蒙戈游樂場
您沒有提供所需的確切輸入和輸出,因此這將需要一些小的更改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396467.html
上一篇:除了遍歷MongoDB的游標之外,還有什么更好的方法嗎?
下一篇:如何更新貓鼬中的嵌套陣列值?
