In MongoDB the $count
aggregation operator passes a document to the next stage in the aggregation pipeline that contains a count of the number of documents input to the current stage.
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 aggregation operation to count the number of dogs in the collection:
db.pets.aggregate([
{
$match: { type: "Dog" }
},
{
$count: "DogCount"
}
])
Result:
{ "DogCount" : 4 }
The way the aggregation pipeline works is that it consists of stages. Each pipeline stage provides the input for the next stage.
Therefore, in the above example, the first stage filtered the collection down to just those documents that had a type
of dog
. The second stage took those documents, counted them, and passed the result to the next stage. Given it was the last stage in the pipeline, we saw the output.
Counting Grouped Documents
Here’s an example that combines the $group aggregate operator with $count to return a count of each type of pet under a certain weight.
db.pets.aggregate([
{
$match: { weight: { $lt: 30 } }
},
{
$group: { _id: "$type", count: { $sum: 1 } }
}
])
Result:
{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bat", "count" : 1 }
{ "_id" : "Dog", "count" : 3 }
Add a Pipeline Stage
In this example, we add a pipeline stage to sort the results. In particular, we use the $sort
operator to do this.
db.pets.aggregate([
{
$match: { weight: { $lt: 30 } }
},
{
$group: { _id: "$type", count: { $sum: 1 } }
},
{
$sort : { count : -1, _id: 1 }
}
])
Result:
{ "_id" : "Dog", "count" : 3 }
{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bat", "count" : 1 }
In this case, we sorted by the count in descending order (the -1
specifies descending order), then by _id
in ascending order (the 1
specifies ascending order).
More Information
See the MongoDB documentation for more information.