In MongoDB the count
aggregation command counts the number of documents in a collection or a view.
It returns a document that contains the count as well as the command status.
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.runCommand( { count: "pets" } )
Result:
{ "n" : 7, "ok" : 1 }
The MongoDB documentation actually recommends against using the count
command and its wrapper methods without a query predicate. This is because, when run without a query predicate, it returns results based on the collection’s metadata, which may result in an approximate count.
Count the Result of a Query
You can count the result of a query by using the following form.
Example:
db.runCommand( {
count: "pets",
query: { type: "Dog" }
} )
Result:
{ "n" : 4, "ok" : 1 }
In this example, we can see 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.runCommand( { count:'pets',
query: { weight: { $gt: 10 } }
} )
Result:
{ "n" : 3, "ok" : 1 }
Limit the Count
You can use the limit
parameter to specify a maximum number of documents to count.
Example:
db.runCommand( {
count: "pets",
query: { type: "Dog" },
limit: 3
} )
Result:
{ "n" : 3, "ok" : 1 }
We saw before that there are actually 4 dogs, but in this example we limited it to count a maximum of 3.
If the limit is higher than the actual count, then the result won’t be affected by the limit
argument.
Example:
db.runCommand( {
count: "pets",
query: { type: "Dog" },
limit: 10
} )
Result:
{ "n" : 4, "ok" : 1 }
Skipping Documents
You can use the skip
parameter to skip a number of documents before counting.
Example:
db.runCommand( {
count: "pets",
query: { type: "Dog" },
skip: 2
} )
Result:
{ "n" : 2, "ok" : 1 }
Deprecation
Note that the MongoDB documentation states the following:
MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection
count()
APIs (which runs thecount
command) in favor of new APIs that corresponds tocountDocuments()
andestimatedDocumentCount()
. For the specific API names for a given driver, see the driver API documentation.
More Information
The count
command includes other fields, such as hint
, comment
, readConcern
, and collation
.
See the MongoDB documentation for more information.