Why does "estimatedDocumentCount()" get a different result than "count()" and "countDocuments()"?

db.solarSystem.count({type:{$ne:“Star”}}) //8
db.solarSystem.countDocuments({type:{$ne:“Star”}}) //8
db.solarSystem.estimatedDocumentCount({type:{$ne:“Star”}}) //9
db.solarSystem.find({type:{$ne:“Star”}}).count() //8

Hi @Jin_Xin_Chen and welcome to the MongoDB Community forums. :wave:

Taking a look at the estimatedDocumentCount() documentation, we see the following:

db.collection.estimatedDocumentCount() does not take a query filter and instead uses metadata to return the count for a collection.

Since it’s using metadata the count may not be correct. This also explains the estimated portion of the name. It’s returning a best guess answer without running the actual filtered query.

4 Likes

Hi @Jin_Xin_Chen,

The estimatedDocumentCount() result is based on metadata for the count of all documents in a collection.

As noted in the documentation @Doug_Duncan quoted, this method does not take a query filter so it is not equivalent to your other counts which filter on type values. Your query document is being interpreted as the options parameter for estimatedDocumentCount() and ignored.

You could compare with db.solarSystem.countDocuments(), which would be an accurate count of all documents (versus a fast but possibly inaccurate estimate).

Regards,
Stennie

2 Likes

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