Mongoose: Unify best practices for countDocuments() and estimatedDocumentCount()

Created on 19 Jul 2018  路  6Comments  路  Source: Automattic/mongoose

Re: discussion from https://github.com/Automattic/mongoose/issues/6713, leaving a note to think about whether we should add a method that switches between countDocuments() and estimatedDocumentCount() based on whether filter is empty or not.

discussion

Most helpful comment

There's some more detail about why you would use one vs the other in the API docs:

TLDR; estimatedDocumentCount() is faster when you're looking to count how many documents are in the entire collection, but might not be 100% accurate in a sharded cluster. If you're using a standalone MongoDB instance and have less than 100k documents per collection, it doesn't make much difference whether you use estimatedDocumentCount() or countDocuments(). It can make a big difference with large collections though.

All 6 comments

I agree with this issue, I don't understand why I have to switch between two functions.

There's some more detail about why you would use one vs the other in the API docs:

TLDR; estimatedDocumentCount() is faster when you're looking to count how many documents are in the entire collection, but might not be 100% accurate in a sharded cluster. If you're using a standalone MongoDB instance and have less than 100k documents per collection, it doesn't make much difference whether you use estimatedDocumentCount() or countDocuments(). It can make a big difference with large collections though.

use count(0) instead of count({filter}) or countDocument({filter}) to run estimatedDocumentCount()

Is it the best practice to use estimatedDocumentCount() when there is no query parameter?
If it is, it will be very helpful to switch between estimatedDocumentCount() and countDocuments() with a single method.

@libook yes, you should use estimatedDocumentCount when there's no filter param. There may be some reasons to use countDocumenta() if you're using sharding, but I'm not certain.

CountDocuments

Was this page helpful?
0 / 5 - 0 ratings