Rachel
Rachel

Reputation: 31

Mongoose count number of returned array?

User.find({job:"developer",sick:1},callback);

Above query gave me numbers of arrays object, but I just need the length of it. I tried User.count({job:"developer",sick:1},callback); it doesn't work.

I know I can use native .length native function but I want to use count() to optimize my query.

Upvotes: 1

Views: 1435

Answers (2)

Tim
Tim

Reputation: 2715

Just use count function if you dont want to use .length

User.count({job:"developer",sick:1}, function(err, count) {
   console.log(count);
});

Some users (@Jasch1) recommend to use this:

Song.find({job: 'developer'}, {sick: 1}, function(err, docs){
    var length = docs.length;
    console.log(length);
})

However one thing to remember that .count returns number where .find actually returns actual data which could be very inefficient if you have big collection.

Upvotes: 0

Jasch1
Jasch1

Reputation: 573

I think it would be something like this.

var query = {job:"developer",sick:1};
User.count(query, function(err, count) {
    if(err) console.log(err);
    console.log(count);
});

The better way(depending on if you want to use the returned documents) is to use .length. However, if you are just doing this for speed then count is probably better.

To do it with .length:

User.find({job: 'developer'}, {sick: 1}, function(err, docs){
    var length = docs.length;
    console.log(length);
})

The Difference

.count() will only return the length without making a full query and loading the documents, while .length will take a returned array and get the length, which could take longer depending on what is being stored in your database

Upvotes: 3

Related Questions