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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)