Difference between count() and find().count() in MongoDB

Abhiram mishra picture Abhiram mishra · Sep 19, 2015 · Viewed 71.5k times · Source

What is the difference between, I basically wanted to find all the documents in the mycollection. db.mycollection.count() vs db.mycollection.find().count()?

They both returns the same result. Is there any reason why would somebody choose the count() vs the find().count()? In contrast to the fact that find() has a default limit applied (correct me if I'm wrong) to which you would have to type "it" in order to see more in the shell.

Answer

styvane picture styvane · Sep 19, 2015

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 same will return the same query argument, will return the same the 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 worth mentioning that the estimatedDocumentCount output can be inaccurate as mentioned in the documentation.