Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

384
Views
Mongodb: How can i check if a count is smaller than a value

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]}}}
    ]);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!