0
0
MongoDBquery~5 mins

countDocuments method in MongoDB

Choose your learning style9 modes available
Introduction

The countDocuments method helps you find out how many documents match a certain condition in a MongoDB collection. It's like counting how many items fit your search.

You want to know how many users have signed up with a specific email domain.
You need to count how many orders were placed in the last month.
You want to check how many products are currently in stock.
You want to find out how many blog posts have a certain tag.
You want to count how many customers live in a particular city.
Syntax
MongoDB
db.collection.countDocuments(filter, options)

filter is where you specify the condition to match documents.

options is optional and can include settings like limit or skip.

Examples
Counts how many users are 18 years old or older.
MongoDB
db.users.countDocuments({ age: { $gte: 18 } })
Counts how many orders have the status "shipped".
MongoDB
db.orders.countDocuments({ status: "shipped" })
Counts up to 100 products in the "books" category.
MongoDB
db.products.countDocuments({ category: "books" }, { limit: 100 })
Sample Program

This query switches to the shopDB database and counts all customers whose city is "New York".

MongoDB
use shopDB

// Count how many customers live in 'New York'
db.customers.countDocuments({ city: "New York" })
OutputSuccess
Important Notes

countDocuments only counts documents that match the filter exactly.

It is more accurate than estimatedDocumentCount() when you use filters.

If you want to count all documents without a filter, you can call countDocuments({}).

Summary

countDocuments tells you how many documents match your search.

You give it a filter to specify what to count.

It helps you quickly get counts without fetching all data.