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.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (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
- Deprecated — use countDocuments() in new code
- Semantically equal to countDocuments() but possibly less precise on shards
- count() does not consume the cursor; iteration can continue
🏷️ Related Tags
💡 Related Cases
Mongoose Advanced Patterns: Performance and Flexibility
Performance Optimization and Monitoring: Production-Level Tuning
📚 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.