For a full overview of MongoDB and all my posts on it, check out my overview.
MongoDB has a few ready-made aggregations available as methods and one of those is count
. It can be used to determine how many documents are in a collection or returned from a query.
Given this data set in a collection called cats
:
{
"name": "Mocha",
"age": 3,
"breed": "Domestic Longhair",
"furPattern": "Turtoiseshell"
},
{
"name": "Latte",
"age": 3,
"breed": "Maine Coon",
"furPattern": "Turtoiseshell"
},
{
"name": "Trouble",
"age": 12,
"breed": "Domestic Shorthair",
"furPattern": "Black"
}
To get the count of all the documents in the cats
collection:
db.cats.count()
To get the count of the number of documents returned from a query:
db.cats.find({age: 3}).count()
You can also pass a query directly into the count method instead of chaining off of find
:
db.cats.count({age: 3})
Top comments (0)