[英]Is there a way to query documents in mongoDB/mongoose to match ALL objects in an array property WHERE the datetime is greater than a specified date
[英]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”属性上。 该属性可以被索引,这使得它更有效率。
使用可以像这样使用$where :
await EmployeeSchema.find( {$where:'this.departments.length>0'} )
如果有人正在寻找数组长度大于一个值,你可以像下面这样做,
db.collection.find({ field : { $size: { $gt : 0 } }})
上述查询将检查该字段中是否至少有一个值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.