MongoDB count() versus countDocuments()

The db.collection.find method returns a cursor. The cursor.count() method on the cursor counts the number of documents referenced by a cursor. This is same as the db.collection.count().

Both these methods (the cursor.count() and db.collection.count()) are deprecated as of MongoDB v4.0. From the documentation:

MongoDB drivers compatible with the 4.0 features deprecate their
respective cursor and collection count() APIs in favor of new APIs for
countDocuments() and estimatedDocumentCount(). For the specific API
names for a given driver, see the driver documentation.

Avoid using the db.collection.count() method without a query predicate
since without the query predicate, the method returns results based on
the collection’s metadata, which may result in an approximate count.

db.collection.countDocuments(query) returns the count of documents that match the query for a collection or view. This is the method you need to use to count the number of documents in your collection.

All of the above return the exact same thing.

Yes, most of the times. Only, the countDocuments returns the actual count of the documents. The other methods return counts based upon the collection’s meta data.

If you want to use db.collection.count, use it with a query predicate, and this will return the exact count of the documents (but, note that this method is deprecated).

Leave a Comment