Upsert operation guide - insert if it does not exist, update if it exists
📋 Quick Answer
To implement "insert if it does not exist, update if it exists" use the following method:
⭐ Recommended method: findOneAndUpdate() + upsert: true
🎯 All methods that support Upsert
💡 Detailed usage
About
updateMany()upsert: MongoDB supportsupdateMany(filter, update, { upsert: true }), but the no-match branch inserts a single document derived fromfilterandupdate. It is not a per-input bulk upsert. For many independent keys, prefer repeatedupsertOne()calls or nativebulkWriteupdateOneoperations withupsert: true.
1. findOneAndUpdate() - Recommended ⭐⭐⭐⭐⭐
Advantages:
- ✅ Atomic operations
- ✅ Return to document content
- ✅ Can get the inserted _id
- ✅ Support
$setOnInsert
Basic Usage:
Get whether it is a new insertion:
2. updateOne() - Simple scene ⭐⭐⭐⭐
Advantages:
- ✅ Good performance (does not return documents)
- ✅ Return to operation statistics
Basic Usage:
3. replaceOne() - Replace the entire document ⭐⭐
Advantages:
- ✅ Completely replace the document (without using the update operator)
Usage:
🎯 Common usage scenarios
Scenario 1: User configuration
Scenario 2: Counter
Scenario 3: Product inventory
Scenario 4: Cache Management
Scenario 5: Daily check-in
⚠️ IMPORTANT NOTES
1. The update operator must be used
2. Use of $setOnInsert
$setOnInsert only takes effect when inserting a new document:
3. Unique index conflict
📊 Performance comparison
🎯 Best Practices
1. Prioritize the use of findOneAndUpdate()
Recommended in most cases because:
- Can obtain document content
- Support
$setOnInsert - Atomic operation guaranteed
2. Use updateOne() in performance optimization scenarios
If you just need to know if it was successful: