1
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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

11 Comments

you should read Mongoose Doc (mongoosejs.com/docs/api.html#model_Model.count) before making such statement.
I know your way will work, it is just not the best way to do it
Well your method wont work for the simple fact that mongoose async framework and your length would be null
what is the different using .length of javascript native function?
I would recommend using its native function just because it would allow you to work with the data and not just return the length. It would be slower but depending on what you want to do it may be better. I added some stuff to my answer to explain the difference
|
0

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.

1 Comment

@Rachel ok does this work? User.find({job:"developer",sick:1},function(err, items){console.log(items)});

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.