Home > Mobile >  Find documents having a field greater than the length of an embeded array
Find documents having a field greater than the length of an embeded array

Time:09-26

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?

CodePudding user response:

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.

  • Related