1 min read

How to count the number of documents in a MongoDB collection or query

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})

Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here