Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Geoff Avatar asked Mar 08 '13 18:03

Geoff


People also ask

How do I limit the number of records in MongoDB?

To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

How does limit work in MongoDB?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.

What method can we use to maximize performance and prevent MongoDB from returning more results than required for processing?

Limit the Number of Query Results to Reduce Network Demand MongoDB cursors return results in groups of multiple documents. If you know the number of results you want, you can reduce the demand on network resources by issuing the limit() method.

How many documents is too many in MongoDB?

To my knowledge, there's no real 'limit' on the number of docs in a collection.. probably, it is the number of unique combinations of _id field MongoDB can generate..But that would be much larger than 500K..


1 Answers

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.

like image 172
johnnycrab Avatar answered Sep 21 '22 23:09

johnnycrab