Mongoose 查找 array.length 大于 0 & 的所有文档对数据进行排序 [英] Mongoose find all documents where array.length is greater than 0 & sort the data
问题描述
我正在使用 mongoose 在 MongoDB 上执行 CRUD 操作.这就是我的架构的外观.
I am using mongoose to perform CRUD operation on MongoDB. This is how my schema looks.
var EmployeeSchema = new Schema({
name: String,
description: {
type: String,
default: 'No description'
},
departments: []
});
每个员工可以属于多个部门.Departments 数组看起来像 [1,2,3].在这种情况下,departments.length = 3.如果员工不属于任何部门,则departments.length 将等于0.
Each employee can belong to multiple department. Departments array will look like [1,2,3]. In this case departments.length = 3. If the employee does not belong to any department, the departments.length will be equal to 0.
我需要找到 EmployeeSchema.departments.length > 0 & 的所有员工如果查询返回超过 10 条记录,我只需要获取最大部门数的员工.
I need to find all employee where EmployeeSchema.departments.length > 0 & if query return more than 10 records, I need to get only employees having maximum no of departments.
是否可以使用 Mongoose.find() 来获得想要的结果?
Is it possible to use Mongoose.find() to get the desired result?
推荐答案
假设您的模型名为 Employee
:
Employee.find({ "departments.0": { "$exists": true } },function(err,docs) {
})
作为 $exists
请求数组的 0
索引,这意味着它里面有东西.
As $exists
asks for the 0
index of an array which means it has something in it.
同样适用于最大数量:
Employee.find({ "departments.9": { "$exists": true } },function(err,docs) {
})
因此需要在数组中至少有 10 个条目才能匹配.
So that needs to have at least 10 entries in the array to match.
实际上,您应该记录数组的长度并在每次添加内容时使用 $inc
进行更新.然后你可以这样做:
Really though you should record the length of the array and update with $inc
every time something is added. Then you can do:
Employee.find({ "departmentsLength": { "$gt": 0 } },function(err,docs) {
})
在您存储的departmentsLength"属性上.该属性可以编入索引,从而提高效率.
On the "departmentsLength" property you store. That property can be indexed, which makes it much more efficient.
这篇关于Mongoose 查找 array.length 大于 0 & 的所有文档对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!