Faster counts in large MongoDB collections

Eric Lu
1 min readFeb 15, 2017

Here’s a query that takes forever for a podcast database. I want to know the number of podcasts that start with the letter A:

// hangs and eventually times out
db.podcasts.find({'name': {'$regex': /^A/i}}.count()

But, if I limit the fields returned, this returns more quickly:

// returns in 2.47s
db.podcasts.find({'name': {'$regex': /^A/i}}, {}).count()

Counting large collections is unfortunately slow, but sometimes necessary for things like pagination and research. I hope this helps!

--

--