繁体   English   中英

如何在 mongodb 聚合中的 $sum 中使用 $match?

[英]How to use $match inside $sum in mongodb aggregation?

这是我写的一个查询,用于查找正确答案的数量。

const response = await Response.aggregate([
            {
                $match: {
                    userID: `${userID}`,
                    quizID: `${quizID}`
                }
            },
            {
                $project: {
                    res: "$response.status",
                    result: {
                       correct: {"$sum": "correct"}, // here I need number of correct ans
                       incorrect: {"$sum": "wrong"} // no of wrong ans
                    }
                }
            }
        ]);

以下是我的回复文件

{
            "_id": "6062e68c132e2d61d168df1d",
            "quizID": "6062a21d697cd216b4ce2a6a",
            "response": [
                {
                    "questionID": [
                        "605dcfe57ad11ec729147b2e"
                    ],
                    "_id": "6062e68c132e2d61d168df1e",
                    "userResponse": 1,
                    "status": "correct"
                },
                {
                    "questionID": [
                        "6060784b59026c2a238174f9"
                    ],
                    "_id": "6062e68c132e2d61d168df1f",
                    "userResponse": 3,
                    "status": "wrong"
                },
                {
                    "questionID": [
                        "6060786159026c2a238174fd"
                    ],
                    "_id": "6062e68c132e2d61d168df20",
                    "userResponse": 2,
                    "status": "wrong"
                }
            ],
            "userID": "605da5b08174cf7c1f67100d",
            "__v": 0
        }

当前查询返回

{
            "_id": "6062e68c132e2d61d168df1d",
            "res": [
                "correct",
                "wrong",
                "wrong"
            ],
            "result": {
                "correct": 0,
                "incorrect": 0
            }
        }

我如何让它返回“正确”答案和“错误”答案的计数?

您需要先$filter数组,然后使用$size获取项目总数:

correct: { 
    $size: { 
        $filter: { 
            input: "$response.status", 
            cond: { $eq: [ "$$this", "correct" ] } 
        } 
    } 
}

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM