findAndCount
A convenience method that returns query results and the total count at the same time. It runs find() and countDocuments() in parallel and is well suited for pagination scenarios.
Basic Usage
Parameters
query (Object)
Query criteria, identical to find().
options (Object)
Query options:
projection/project(Object) - field projection.projectis an alias forprojection;projectionwins when both are provided.sort(Object) - sort ruleslimit(Number) - maximum number of returned documents (undefinedmeans no limit)skip(Number) - number of documents to skipcache(Number) - cache duration in millisecondsmaxTimeMS(Number) - query timeoutcomment(String) - query comment
Return Value
Returns a Promise that resolves to an object with the following fields:
data(Array) - query result arraytotal(Number) - total number of documents that match the criteria
Examples
Paginated Query
With Projection and Sorting
Enable Cache
Performance Benefits
- ✅ Runs
find()andcountDocuments()in parallel, which is faster than serial execution - ✅ Supports automatic caching, making repeated queries faster
- ✅ Reduces boilerplate by completing the operation with one call
Notes
limitisundefined- does not limit the number of returned documents and queries all matcheslimitis0- means no limit in MongoDB and returns all data- Cache key - includes query, projection, sort, limit, and skip
- Best-fit scenarios - paginated queries and list views
Comparison with the Traditional Approach
❌ Traditional Approach (Two Calls)
✅ findAndCount (One Call, Parallel Execution)
Related Methods
- find - query documents
- findOne - query a single document
- findPage - cursor pagination query
- count - count documents
Test Coverage
- ✅ Basic functionality: 6 tests
- ✅ Pagination scenarios: 4 tests
- ✅ Edge cases: 4 tests
- ✅ Cache functionality: 1 test
- ✅ Parameter validation: 2 tests
- ✅ Performance test: 1 test
Test coverage: 100%