CodeNewbie Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

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

Enter fullscreen mode Exit fullscreen mode

To get the count of all the documents in the cats collection:

db.cats.count()

Enter fullscreen mode Exit fullscreen mode

To get the count of the number of documents returned from a query:

db.cats.find({age: 3}).count()

Enter fullscreen mode Exit fullscreen mode

You can also pass a query directly into the count method instead of chaining off of find:

db.cats.count({age: 3})

Enter fullscreen mode Exit fullscreen mode

Discussion (0)