How to use $match inside $sum in mongodb aggregation?

Viewed 180

This is a query I have written to find the number of correct answers.

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
                    }
                }
            }
        ]);

Below is my response document

{
            "_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
        }

The current query returns

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

How do I get it to return the count of "correct" ans and "wrong" ans?

1 Answers

You need to $filter your array first and then use $size to get total number of items:

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

Mongo Playground

Related