insertBatch - batch insertion (supports automatic retry)
API parameter description
Method signature
Detailed explanation of parameters
First parameter: documents (required)
- Type:
object[] - Description: Array of documents to be inserted
Second parameter: options (optional)
Return value
Progress callback parameters
Usage example
1. Basic usage - automatic batch insertion
2. Progress monitoring
3. Automatic retry mechanism ⭐ New features
3.1 retry strategy - automatic retry on failure
4. Comparison of error handling strategies
4.1 stop strategy (default) - stop on error
4.2 skip strategy - skip failed batches
4.3 collect strategy - collect all errors
5. Concurrent insertion (accelerate big data import)
6. Combined with comment parameter (production environment)
Comparison of error handling strategies
Strategy Selection Guide
Performance optimization suggestions
1. Batch size (batchSize)
Selection Guide:
- Small document (< 1KB):
batchSize: 1000-2000 - Chinese Document (1-10KB):
batchSize: 500-1000 - Large Document (> 10KB):
batchSize: 100-500
2. Concurrency control (concurrency)
3. Retry policy configuration
FAQ
Q: How to choose insertBatch vs insertMany?
A: Select based on data volume:
- < 5K items: Use
insertMany(easier) - 5K-50K items: Use
insertBatch(safer) - > 50K items: Must use
insertBatch(to avoid timeouts)
Q: How to set batchSize?
A: Consider the following factors:
- Document size: The larger the document, the smaller
batchSize - Network speed: The slower the network, the smaller the
batchSize - Database Performance: The weaker the database, the smaller
batchSize - Recommended starting point: Use
1000first, and adjust according to the actual situation
Q: When should the retry mechanism be used?
A: The following scenarios are suitable for retrying:
- ✅ Network instability (WiFi, mobile network)
- ✅ High database load (temporary connection failure)
- ✅ Lock conflict (may succeed after waiting)
- ❌ Data error (retry will not succeed)
- ❌ Permission problem (retry will not succeed)
Q: Will concurrency lead to data inconsistency?
A: No. insertBatch ensures:
- Each batch is inserted independently
insertedIdsis mapped in original order- Error handling is associated with batches
- Explicit cache invalidation is supported
Q: How to deal with partial failure?
A: Use collect or retry strategy:
References
- batch operations runnable example - Current TypeScript example
- test/unit/writes/batch.test.ts - test case
- Write operations guide - Overview of write operations
- Cache system - Cache invalidation mechanism
- insertBatch improvement notes - Suggestions for further improvements