繁体   English   中英

Mongoose 查找 array.length 大于 0 的所有文档并对数据进行排序

[英]Mongoose find all documents where array.length is greater than 0 & sort the data

我正在使用 mongoose 在 MongoDB 上执行 CRUD 操作。 这就是我的架构的外观。

var EmployeeSchema = new Schema({
      name: String,
      description: {
        type: String,
        default: 'No description'
      },
      departments: []

    });

每个员工可以属于多个部门。 Departments 数组看起来像 [1,2,3]。 在这种情况下,部门长度 = 3。如果员工不属于任何部门,部门长度将等于 0。

我需要找到所有员工,其中 EmployeeSchema.departments.length > 0 & 如果查询返回超过 10 条记录,我只需要获得最多部门数的员工。

是否可以使用 Mongoose.find() 来获得所需的结果?

假设您的模型名为Employee

Employee.find({ "departments.0": { "$exists": true } },function(err,docs) {

})

因为$exists要求数组的0索引,这意味着它里面有东西。

这同样适用于最大数量:

Employee.find({ "departments.9": { "$exists": true } },function(err,docs) {

})

所以需要在数组中至少有 10 个条目才能匹配。

确实,尽管您应该记录数组的长度并在每次添加内容时使用$inc更新。 然后你可以这样做:

Employee.find({ "departmentsLength": { "$gt": 0 } },function(err,docs) {

})

在您存储的“departmentsLength”属性上。 该属性可以被索引,这使得它更有效率。

由于某种原因,选定的答案目前不起作用。 $size 运算符

用法:

collection.find({ field: { $size: 1 } });

将查找长度为 1 的数组。

使用可以像这样使用$where

await EmployeeSchema.find( {$where:'this.departments.length>0'} )

如果有人正在寻找数组长度大于一个值,你可以像下面这样做,

db.collection.find({ field : { $size: { $gt : 0 } }})

上述查询将检查该字段中是否至少有一个值

暂无
暂无

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

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