Search code examples
mongodbcountlimit

Limiting results in MongoDB but still getting the full count?


For speed, I'd like to limit a query to 10 results

db.collection.find( ... ).limit(10)

However, I'd also like to know the total count, so to say "there were 124 but I only have 10". Is there a good efficient way to do this?


Solution

  • By default, count() ignores limit() and counts the results in the entire query. So when you for example do this, var a = db.collection.find(...).limit(10); running a.count() will give you the total count of your query.