Search code examples
mongodbmongodb-query

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


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

They both return the same result. Is there any reason why somebody would 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.


Solution

  • 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.