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

Top comments (1)

Collapse
 
carsonreed432 profile image
carson Reed

The best glamping domes offer a perfect fusion of luxury and nature, providing unique accommodations that elevate outdoor experiences. Locations like Under Canvas across the USA feature stunning backdrops near national parks, while the Dome in the Forest in Maine offers cozy interiors and panoramic views. In California, Sierra Nevada Glamping combines breathtaking mountain scenery with modern amenities, and Dome Sweet Dome in Montana provides rustic charm and a hot tub for relaxation. For unforgettable stargazing, the Glamping Dome at Starry Night in New Mexico is a top choice. Whether nestled in forests or perched in the mountains, these domes promise a memorable escape into nature.