count Method Reference
Overview
count is a statistical query method provided by monSQLize. It quickly counts the number of MongoDB collection documents that match specific criteria. Internally, it uses MongoDB's recommended native countDocuments() and estimatedDocumentCount() methods, and supports index hints, caching, performance optimization, and related options.
Method Signature
Parameters
query Parameter
Query criteria object using standard MongoDB query syntax.
Type: Object
Required: No
Default: {}. An empty object counts all documents.
Examples:
options Parameter Object
Legend:
- ✅ MongoDB native: a standard feature supported by official MongoDB APIs
- 🔧 monSQLize extension: functionality provided by monSQLize
MongoDB references:
Performance Optimization Notes
Automatic method selection:
- When
queryis an empty object{}, monSQLize automatically usesestimatedDocumentCount(), which is based on collection metadata and has the best performance - When
querycontains criteria, monSQLize usescountDocuments(), which provides accurate counts and supports indexes
comment Configuration
Query comments identify the purpose of count queries in MongoDB logs:
Use cases:
- Dashboard metrics: identify the source of metric queries
- Scheduled jobs: identify scheduled count tasks
- Monitoring alerts: identify count queries from monitoring systems
- Data analysis: identify analytics-related counts
Examples:
Reference: for the complete comment guide, see the find method documentation.
hint Configuration
Forces MongoDB to use a specific index. This applies only when countDocuments is used:
Use cases:
- The MongoDB query optimizer picked the wrong index
- A specific index must be forced to guarantee performance
- You need to compare the performance of different indexes
skip and limit Configuration
Controls the range of documents being counted. This applies only when countDocuments is used:
Use cases:
- Paginated counting, such as counting only the current page
- Sample counting, such as counting only part of the matched documents
collation Configuration
Specifies string comparison rules:
Common scenarios:
- Case-insensitive counting
- Correct counting in multilingual environments
Return Value
Normal Mode Returns a Number
By default, count returns a Promise that resolves to the number of matching documents:
Return type: Promise<number>
explain Mode Returns the Execution Plan
When explain is true or a specific verbosity level, the method returns the query execution plan:
Return type: Promise<Object>
Usage Patterns
1. Basic Counts
The simplest count patterns:
Applicable scenarios:
- Count the total number of documents in a collection
- Count documents that match criteria
- Generate data overviews and reports
2. Complex Conditional Counts
Build complex counts with MongoDB query operators:
3. Index Optimization
Use hint to force an index and explain to inspect the execution plan:
Performance optimization recommendations:
- Create indexes for commonly counted fields
- Use compound indexes to optimize multi-condition counts
- Regularly analyze slow queries and optimize indexes
- Empty queries automatically use
estimatedDocumentCount, which has the best performance
4. Cache Usage
Enable caching to improve count performance:
Cache strategy:
- Enable caching for frequently counted data that changes infrequently
- Set a reasonable TTL
- Pay attention to cache invalidation
- Use
invalidate()to clear cache after data updates
5. Performance Comparison: Empty Query Optimization
monSQLize automatically optimizes empty queries with no criteria:
Performance difference:
estimatedDocumentCount: millisecond-level, based on collection metadatacountDocuments: can take seconds on large datasets because it needs to scan documents or indexes
Error Handling
The count method may throw the following errors:
Common errors:
NOT_CONNECTED: the database is not connected- Query timeout errors on large datasets
- Permission-related errors
- Invalid query criteria errors
Performance Optimization Recommendations
1. Index Optimization
2. Query Criteria Optimization
3. Cache Strategy
4. Timeout Settings
5. skip and limit Optimization
Best Practices
- Create indexes for counted fields: make sure fields used in criteria have suitable indexes
- Use cache to reduce load: enable caching for frequent counts where data changes infrequently
- Avoid full collection scans: count through indexed fields whenever possible
- Set timeout protection: configure
maxTimeMSfor large counts - Monitor slow queries: use
explainto analyze count performance - Optimize empty queries: take advantage of
estimatedDocumentCount
FAQ
Q: What is the difference between count and estimatedDocumentCount?
A: monSQLize handles this automatically:
- Empty
count()calls automatically useestimatedDocumentCount, which is fast and metadata-based - Conditional queries automatically use
countDocuments, which is accurate and scans indexes or documents
Q: How can I improve count performance on large datasets?
A:
- Create indexes for queried fields
- Use caching to reduce repeated counts
- Consider using aggregation pipelines to precompute statistics
- Update counts asynchronously when real-time accuracy is not required
Q: Does count scan all documents?
A:
- With an index: it scans only the index, not the documents
- Without an index: it needs to scan all documents
- Empty query: it uses collection metadata and does not scan documents
Related Methods
find(): query multiple recordsfindOne(): query a single recordfindPage(): paginated queryaggregate(): aggregation query for more complex statisticsinvalidate(): invalidate cache
Example Code
For the complete usage example, see examples/docs/count.ts.
Test Cases
For the complete test cases, see test/integration/mongodb/queries.test.ts.