findOne Method Reference
Overview
findOne is a basic query method provided by monSQLize. It queries the first document that matches the criteria from a MongoDB collection and supports query criteria, sorting, projection, caching, and related options.
Method Signature
Parameters
query Parameter
Type: Object
Default: {}
Required: No
MongoDB query criteria object. All MongoDB query operators are supported.
Examples:
options Object Properties
Legend:
- ✅ MongoDB native: a standard feature supported by official MongoDB APIs
- 🔧 monSQLize extension: functionality provided by monSQLize
MongoDB reference:
comment Configuration
Query comments identify the query source in MongoDB logs, which helps production operations, monitoring, and performance analysis:
Use cases:
- Business scenario identification: identify which page or feature issued the query
- User tracing: record the user or session associated with the query
- Distributed tracing: associate the query with a complete request chain through a traceId
- Performance analysis: locate issues quickly in slow-query logs
Examples:
Reference: for the complete comment guide, see the find method documentation.
projection Configuration
Projection controls which fields are included in or excluded from the query result. Two formats are supported:
Object format:
Array format:
Notes:
- MongoDB does not allow mixing inclusion (
1) and exclusion (0), except for the_idfield - The array format is automatically converted to inclusion mode
- The
_idfield is always included by default unless explicitly excluded with{ _id: 0 }
sort Configuration
Sort configuration defines how results are ordered:
Performance recommendations:
- For large datasets, make sure the sorted fields are indexed
- Avoid sorting on unindexed fields
- Use compound indexes to optimize multi-field sorting
hint Configuration
Forces MongoDB to use the specified index:
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
collation Configuration
Specifies string comparison and sorting rules:
Common scenarios:
- Case-insensitive queries and sorting
- Correct ordering in multilingual environments
- Natural sorting for numeric strings
Return Value
Normal Mode Returns an Object or null
By default, findOne returns a Promise that resolves to the first matching document or null:
Return type: Promise<Object|null>
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 Query
The simplest query pattern returns the first matching document:
Applicable scenarios:
- Query one record by a unique identifier
- Get the newest or oldest record
- Check whether a record exists
2. Complex Query Criteria
Build complex queries 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 queried fields
- Use compound indexes to optimize multi-condition queries
- Regularly analyze slow queries and optimize indexes
4. Cache Usage
Enable caching to improve query performance:
Cache strategy:
- Enable caching for frequently queried records that change infrequently
- Set a reasonable TTL
- Pay attention to cache invalidation
Error Handling
The findOne method may throw the following errors:
Common errors:
NOT_CONNECTED: the database is not connected- Query timeout errors
- Permission-related errors
Best Practices
- Always specify sorting: ensure consistent results when multiple records match
- Use projection: return only the required fields to reduce network transfer and memory usage
- Use caching appropriately: enable caching for read-heavy, low-write scenarios
- Create suitable indexes: make sure query performance is predictable
- Handle
nullreturns: check whether the query result isnull
Related Methods
find(): query multiple recordscount(): count recordsfindPage(): paginated queryinvalidate(): invalidate cache