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

我的未来我决定 提交于 2021-02-18 04:07:13

问题


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: []

    });

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.

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.

Is it possible to use Mongoose.find() to get the desired result?


回答1:


Presuming your model is called Employee:

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

})

As $exists asks for the 0 index of an array which means it has something in it.

The same applies to a maximum number:

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

})

So that needs to have at least 10 entries in the array to match.

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) {

})

On the "departmentsLength" property you store. That property can be indexed, which makes it much more efficient.




回答2:


By some reason, selected answer doesn't work as for now. There is the $size operator.

Usage:

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

Will look for arrays with length 1.




回答3:


use can using $where like this:

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


来源:https://stackoverflow.com/questions/31677061/mongoose-find-all-documents-where-array-length-is-greater-than-0-sort-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!