About golang mongo driver CountDocuments

why not use count?why using aggregation group?

Hi @Zheng_Ficoto, and welcome to the forums!

Actually this applies to all MongoDB drivers, not only MongoDB Go driver.

MongoDB drivers compatible with the v4.0+ features deprecate their respective cursor and collection count() APIs in favour of two new APIs:

The reasoning behind the deprecation is because the count() method, when used without a query predicate returns results based on the collection’s metadata which results in an approximate count. On a sharded cluster, the resulting approximation count may not correctly filter out orphaned documents. In addition, after an unclean server shutdown the resulting approximation count may also be incorrect.

The new API names were chosen to make it clear how they behave and exactly what they do.

The countDocuments() helper does not use the collection metadata, but counts the documents that match the provided query filter using an aggregation pipeline. While the estimatedDocumentCount() helper returns an estimate of the count of documents in the collection using collection metadata (wraps the count command), rather than counting the documents or consulting an index. See also Specifications: CRUD Count API Details for more information.

Back to MongoDB Go driver, you have two choices to use depending on your use case: Collection.CountDocuments() and Collection.EstimatedDocumentCount().

Regards,
Wan.

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.