How to efficiently obtain a count?

If running a query and implementing the itcount() will exhaust the cursor then what would be the most efficient way of obtaining a count ahead of a query that actually retrieves the documents?

Do we just return the _id values to limit the size of the response or is there some other count method to use to only return a number for the total records that exist without returning the document information?

If you recall, in your other thread I posted a link to all the cursor methods in my first post. Have a look.

I had created this to separate the topics. I followed the documentation link and now see the difference with regards to the ‘count’ & ‘itcount’

Counts the number of documents referenced by a cursor. Append the count() method to a find() query to return the number of matching documents. The operation does not perform the query but instead counts the results that would be returned by the query.

Thanks again for the link.

Absolutely valid! :+1:

That’s the ticket!

The other difference is itcount() will count the remaining documents. So if the query is for 100 docs, and you run the first iteration of 20 docs, itcount() will return 80.

1 Like

Thanks for pointing that out. I did not catch it before that the ‘itcount’ returns only the remaining count of documents.

Great tip!