Slow countDocuments

So we are having a small issue with

countDocuments

It seems that they are slower then .count() function.

I am wondering how do I speed it up?

the query i am running is

query = { location:{ $geoWithin:{ $centerSphere: [ [ parseFloat(docs.location.coordinates[0]), parseFloat(docs.location.coordinates[1])], 5 / 6378.1] } } };

The script I am running

var dquery = Q.countDocuments(query).exec(function(err, count){

(Then I need to run the following)

 if(count > 0 ){
                          var random = Math.floor(Math.random() * count);
                          //START ADQUERY
                          console.error(count);
                          console.error(random);
                          var aquery = A.findOne(query).skip(random);
}

});
               

It taking approx 3-4 seconds to run the first part, and because we are injecting the response into

stream.on

However it seems to crash the stream because of the query speed.

I am wondering if any one would have a solution to this issue.

1 answer

  • answered 2020-09-14 09:09 D. SM

    count looks at collection metadata and provides an estimated result.

    countDocuments executes the query and provides an accurate result.

    The performance of countDocuments is similar to performance of find with the same arguments.

    You need to have appropriate indexes in place, etc., same as for find.