DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

1 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More