count command uses in mongodb

How to Use MongoDB Count Command to Count Documents In a Collection?

In this tutorial we will learn how to use MongoDB count aggregation command use-cases and how effectively it can be used. MongoDB count command is used to count the documents in a collection or view. The return result will show us the document with the command status. See below detailed examples to understand it in a better way.

Example
We will use this count command on our collection “Pets”

{ "_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 are going to use the query we have shown below to return the documents number our collection Pets

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

Later we can easily count the return results of our query. See the example below:

db.runCommand( {
count: "pets",
query: { type: "Dog" }
} )

Result

{ "n" : 4, "ok" : 1 }

We see that the result shows we have 4 pets. Now we will run an other query for finding the weight greater than a particular measure. Let’s run that command below:

db.runCommand( { count:'pets',
query: { weight: { $gt: 10 } }
} )

Result

{ "n" : 3, "ok" : 1 }

The next we are going to run the query with a limit parameter to count the document. See the example below:

db.runCommand( {
count: "pets",
query: { type: "Dog" },
limit: 3
} )

Result

{ "n" : 3, "ok" : 1 }

If you see above you will notice the number of dogs is 4 in the result while this result shows the limited number because we limited that by using a limit parameter ‘limit: 3’.  So if the limit parameters is targeting a greater number than the total number the results won’t change. See the following example for that:

db.runCommand( {
count: "pets",
query: { type: "Dog" },
limit: 10
} )

Result

{ "n" : 4, "ok" : 1 }

Skipping a Document by using a skip parameter

The next we will use skipping parameter to skip a document number just before counting. See the example below:

db.runCommand( {
count: "pets",
query: { type: "Dog" },
skip: 2
} )

Result

{ "n" : 2, "ok" : 1 }

Please note we can also use other fields with the count command like hint, comment, readConcern and collection.