'most efficient way to count docs in mongodb

I have a reasonable collection with a 7.1m docs.

I have indexes in place to be able to query and fetch data as needed, all good.

But as soon as i try to count, it slows everything waaaayyy down.

Here is an example, takes about 15ms to return (using mongoose in node):

music.aggregate([
 {
  $match: {
   "data.emails": {
      "$exists": true,
      "$ne": []
   }
 }
 },
 { $sort: { 'data.vertical' : 1},
 { $skip: 0 },
 { $limit: 5 }
])

When I try to run a count the query time increases to around 5 seconds (count needed for basic pagination):

music.countDocuments({
   "data.emails": {
      "$exists": true,
      "$ne": []
   }
 });

When the record count was down under 300k, all was fine.. now with a little over 7 million docs, things slowed down a lot with this count.

Is there a more efficient count option in mongodb?



Solution 1:[1]

If you want to count the document count use countDocuments() function in mongoDB.

music.countDocuments({<query>})

Replace the query and run

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ranul Navojith