count() (Count on Cursor)

Last updated: 2026-10-09

count() (Count on Cursor)

count() counts the documents the current cursor would return: `db.users.find({ age: { $gt: 20 } }).count()`. It works on the cursor, so the find() filter applies first. Note that this method is deprecated — the official replacement `db.users.countDocuments()` is equivalent and more accurate on sharded clusters.

CategoryCursor
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.find(<filter>).count()

Returns:Number of documents the cursor would return (integer).

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// count: count users older than 20
const n = db.users.find({ age: { $gt: 20 } }).count()
print(n)

Output:

35

📌 Notes

📚 Related Tutorials

❓ FAQ

QIs cursor count() still usable?
AIt works but is deprecated; new code should use countDocuments(), which is equivalent and more accurate.
QIs count() different from countDocuments()?
ASemantics are the same exact-count operation; countDocuments() is the recommended replacement, more reliable on shards.
QCan I still fetch data after count()?
AYes — count() only tallies, leaving the cursor usable for toArray()/forEach() afterwards.
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%

🙏 帮我们做得更好

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

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