Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 883
SharpCoder Avatar asked Jul 28 '15 12:07

SharpCoder


3 Answers

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.

like image 147
Blakes Seven Avatar answered Nov 17 '22 04:11

Blakes Seven


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.

like image 29
Georgiy T. Avatar answered Nov 17 '22 04:11

Georgiy T.


use can using $where like this:

await EmployeeSchema.find( {$where:'this.departments.length>0'} )
like image 1
Mohammad Yaser Ahmadi Avatar answered Nov 17 '22 05:11

Mohammad Yaser Ahmadi