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

124
Views
Find documents having a field greater than the length of an embeded array

Below is a group schema:

GroupSchema{
    membersLimit: Number,
    listOfStudents: [String]
}

I want to find all the groups where the number of students is less than membersLimit.

I tried the folliowing query

await Group.find({
    membersLimit: { $gt: 'listOfStudents'.length },
})

This query returns documents having students less than 14 i.e. length of listOfStudents.

I also tried this

await Group.find({
    listOfStudents: { $size: { $lt: 'membersLimit' } },
})

This query returns the following error

error The expression evaluated to a falsy value:

  assert.ok(!isNaN(val))

Is there a way to do this with single query?

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to use $expr, to compare the array size and the field, like this:

db.collection.find({
  $expr: {
    $gt: [
      "$membersLimit",
      {
        "$size": "$listOfStudents"
      }
    ]
  }
})

Playground link.

almost 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!