简体   繁体   English

查找字段大于嵌入数组长度的文档

[英]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 .我想找到学生人数少于membersLimit的所有组。

I tried the folliowing query我尝试了以下查询

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

This query returns documents having students less than 14 ie length of listOfStudents .此查询返回学生小于 14 的文档,即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?有没有办法用单个查询来做到这一点?

You need to use $expr , to compare the array size and the field, like this:您需要使用$expr来比较数组大小和字段,如下所示:

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

Playground link .游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM