countDocuments() (Count with Filter)
Last updated: 2026-10-09
countDocuments() (Count with Filter)
countDocuments() counts documents matching a filter, e.g. `db.users.countDocuments({ age: { $gte: 18 } })`. It executes on the server and returns an exact count. Unlike estimatedDocumentCount(), it actually evaluates the filter, so it is precise yet slower — the right choice when accuracy matters. For performance-sensitive queries on huge collections, back the filter with an index.
| Category | Read |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.countDocuments(<filter>, { limit: <number> })
⚙️ Parameters
| filter | Filter to count; empty {} counts everything. |
|---|---|
| limit | Optional. Upper bound on documents counted. |
Returns:Number of matching documents (integer).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// countDocuments: count adult users
const n = db.users.countDocuments({ age: { $gte: 18 } })
print('Adults: ' + n)
Output:
Adults: 42
📌 Notes
- Exact count that truly evaluates the filter — slower than estimatedDocumentCount
- Index the filtered fields to avoid full collection scans
- Pass an empty filter {} for the total document count
🏷️ Related Tags
💡 Related Cases
Document Query Basics: The `find` Method and Projections
RESTful API in Practice: A Complete Guide to CRUD Design
📚 Related Tutorials
❓ FAQ
QHow does countDocuments differ from estimatedDocumentCount?
AcountDocuments() evaluates the filter precisely but slower; estimatedDocumentCount() uses collection metadata — fast but approximate.
QWhy is counting a whole collection with countDocuments not recommended?
AIt must scan matches, which is slow for large collections. When magnitude suffices, use estimatedDocumentCount().
QDoes countDocuments return 0 or throw when nothing matches?
AIt returns 0 without throwing — safe to use in conditionals.