insertOne() - Insert a single document
Syntax
Parameters
document (required)
Type: Object
The document object to be inserted. If the document does not have a _id field, MongoDB will automatically generate one.
options (optional)
Type: Object
Return value
Type: Promise<Object>
Return an object containing the results of the insertion:
Core Features
✅ Automatically generate _id
If the document does not have a _id field, MongoDB automatically generates a unique ObjectId.
✅ Explicit cache invalidation
After the insertion succeeds, monSQLize does not clear query caches by default. Use cache.invalidate or autoInvalidate: true when the write should clear cache.
✅ Slow query monitoring
Insert operations that exceed a threshold (default 1000ms) automatically log warnings.
Common scenarios
Scenario 1: Create new user
Scenario 2: Inserting nested documents
Scenario 3: Using custom _id
Scenario 4: Inserting timestamped documents
Scenario 5: Insert and return complete document
Error handling
Duplicate _id
Invalid document
Unique index conflict
Document verification failed
Differences from other methods
vs insertMany
vs updateOne with upsert
Performance optimization suggestions
1. Use insertMany when inserting in batches
2. Avoid inserting in loops
3. Use appropriate _id type
Best Practices
✅ Contains creation timestamp
✅ Use validation to ensure data quality
✅ Handling duplicate key errors
✅ Use transactions (multiple document insertion)
Notes
⚠️ _id is immutable
Once inserted, the _id field cannot be modified:
⚠️Performance impact of large documents
MongoDB document size is limited to 16MB, but large documents can impact performance:
⚠️ Scope of cache invalidation
autoInvalidate: true clears the entire collection's related cache:
Utility functions
Safe insertion function (with retry)
Related methods
- insertMany() - Batch insert multiple documents
- insertBatch() - high-performance batch insertion (batch processing)
- updateOne() - Update document (insert or update can be achieved with upsert)
Sample code
For complete sample code, please refer to: