Difference between count() and find().count() in MongoDB
db.collection.count()
and cursor.count()
are simply wrappers around the count
command thus running db.collection.count()
and cursor.count()
with/without the same will return the same query argument, will return the same result. However the count
result can be inaccurate in sharded cluster.
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.
The db.collection.countDocuments
method internally uses an aggregation query to return the document count while db.collection.estimatedDocumentCount/
returns documents count based on metadata.
It is worth mentioning that the estimatedDocumentCount
output can be inaccurate as mentioned in the documentation.
db.collection.count()
without parameters counts all documents in a collection. db.collection.find()
without parameters matches all documents in a collection, and appending count()
counts them, so there is no difference.
This is confirmed explicitly in the db.collection.count() documentation:
To count the number of all documents in the orders collection, use the following operation:
db.orders.count()
This operation is equivalent to the following:
db.orders.find().count()
As is mentioned in another answer by sheilak, the two are equivalent - except that db.collection.count()
can be inaccurate for sharded clusters.
The latest documentation says:
count() is equivalent to the db.collection.find(query).count() construct.
And then,
Sharded Clusters
On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.
The documentation explains how to mitigate this bug (use an aggregate).