Home > Back-end >  Mongodb: How can i check if a count is smaller than a value
Mongodb: How can i check if a count is smaller than a value

Time:12-10

I have an assignment for school in which I have to retrieve a list of students which have x amount of failed tests.

A student has a schema like this one student scheme

A failed test is when a student has less than 10 on a course.

The amount here is the amount of fails that is given by the frontend (count of fails has to be more than this amount)

This is what I have but obviously it is not working. I just don't know how to check if the count of the amount of failed tests is bigger than 'amount'

 let amount = 1
    let students = await Student.aggregate([
        {
            $group: {
                _id: '$studentNr',
                count: {"$sum": amount}
            }
        },
        {
            $match: {
                count: {
                    'courses.score':{$lt: 10}
                }
            }
        }
    ]);

thanks in advance

ANSWER

Thanks to Buzz Moschetti I was able to find the correct answer.

    let amount = parseInt(req.body.amount);
    let students = await Student.aggregate([
        {
            $project: {
                name: "$name",
                studentNr: "$studentNr",
                courses: {
                    $filter: {
                        input: "$courses",
                        as: "course",
                        cond: {$lt: ["$$course.score", 10]}
                    }
                }
            }
        },
        {$match: {$expr: {$gt: [{$size:'$courses'}, amount]}}}
    ]);

CodePudding user response:

Fortunately, your schema has all courses scores for each student in an array. So what you need to do is not $group (because each doc as a unique student id) but rather $filter on the courses array and keep only those with score less than 10. After that, you would $match on the $size of the filtered array equal to amount. Since this is homework, I'll leave it there.

  • Related