If you specify a callback method,
estimatedDocumentCount() return nothing. If you do not specify one,
this method returns a
Promise that resolves to the result object
when it completes. See our guide on Promises and Callbacks for more information, or the
API documentation for
information on the result object.
The Node.js driver provides two methods for counting documents in a collection:
- collection.countDocuments() returns the number of documents in
the collection that match the specified query. If you specify an empty
countDocuments()returns the total number of documents in the collection.
- collection.estimatedDocumentCount() returns an estimation of the number of documents in the collection based on collection metadata.
estimatedDocumentCount() is faster than
the estimation uses the collection's metadata rather than scanning the
collection. In contrast,
countDocuments() takes longer to return, but
provides an accurate count of the number of documents and supports
specifying a filter. Choose the appropriate method for your workload.
To specify which documents you wish to count,
accepts a query parameter.
countDocuments() counts the documents that match the specified query.
estimatedDocumentCount() support optional
settings that affect the method's execution. Refer to the reference
documentation for each method for more information.
The following example estimates the number of documents in the
movies collection in the
sample_mflix database, and then returns
an accurate count of the number of documents in the
Canada in the
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
If you run the preceding sample code, you should see the following output:
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349