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.

CategoryRead
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.countDocuments(<filter>, { limit: <number> })

⚙️ Parameters

filterFilter to count; empty {} counts everything.
limitOptional. 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏