In MongoDB the db.collection.countDocuments()
method returns the count of documents that match the query for a collection or view.
The collection
part is the name of the collection or view to perform the count operation on.
Example
Suppose we have a collection called pets
with the following documents:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 } { "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }
We can use the following query to return the number of documents in the collection:
db.pets.countDocuments({})
Result:
7
Count the Result of a Query
You can count the result of a query by passing the query criteria.
Example:
db.pets.countDocuments({
"type": "Dog"
})
Result:
4
In this example, we found out that there are four dogs in the collection.
Let’s check the count of another query. This time we’ll find out how many pets have a weight greater than a certain amount.
db.pets.countDocuments({
"weight": { $gt: 10 }
})
Result:
3
Limit the Count
You use the limit
parameter to specify a maximum number of documents to count.
Example:
db.pets.countDocuments( {}, { limit: 5 } )
Result:
5
We saw before that there are actually 7 documents in this collection, but in this example we limited it to count a maximum of 5.
If the limit is higher than the actual count, then the result won’t be affected by the limit
argument.
Example:
db.pets.countDocuments( {}, { limit: 10 } )
Result:
7
Skipping Documents
You can count use the skip
parameter to skip a number of documents before counting.
Example:
db.pets.countDocuments( {}, { skip: 5 } )
Result:
2
Deprecation of count()
in Favour of countDocuments()
Note that the MongoDB documentation states the following:
MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection
count()
APIs in favor of new APIs forcountDocuments()
andestimatedDocumentCount()
. For the specific API names for a given driver, see the driver documentation.
More Information
The countDocuments()
method doesn’t rely on metadata to return the count like the count()
method does. Instead, it performs an aggregation of the documents, which results in an accurate count (which can’t always be said for the count()
method).
According to the MongoDB documentation, countDocuments()
is accurate even after an unclean shutdown or in the presence of orphaned documents in a sharded cluster.
The db.collection.count()
method also accepts a hint
parameter and a maxTimeMS
parameter.
See the MongoDB documentation for more information.