✅ Implement "insert if it does not exist, update if it exists"
🎯 Quick Answer
Scenario 1: Insert and update using same data (most common) ⭐
If the data is exactly the same when inserting and updating, only $set is needed:
Description:
- ✅ When does not exist: Create a new document containing all fields in
$set - ✅ When exists: Update the existing document and only modify the fields in
$set - ✅ This is the most commonly used method, simple and direct
Scenario 2: Insert and update using different data
If you need to set some extra fields when inserting (such as createdAt), use $setOnInsert:
Description:
- ✅ When it does not exist: Create a new document containing all fields of
$set+$setOnInsert - ✅ When existing: only update the fields in
$set, will not modify the fields in$setOnInsert
📊 Comparison of two scenarios
Selection Suggestions:
- ✅ Use scenario 1 in most cases (only use
$set) - ✅ Use scenario 2 only if you need to distinguish between "fields when inserting" and "fields when updating"
📋 Complete example
Example 1: Same data - product information update ⭐
Example 2: Same data - user status update
Example 3: Different Data - User Configuration Management
Example 3: Different Data - User Profile Management (Full Example)
Example 4: Statistics - Counters
🔍 Determine whether it is a new insertion
📚 Other methods to support Upsert
updateOne() Example
If you do not need to return the document content, you can use updateOne() (better performance):
⚠️ IMPORTANT NOTES
1. The update operator must be used
2. $setOnInsert only takes effect when inserted
📖 Detailed documentation
- Complete Guide to Upsert Operations - Contains all scenarios and best practices
- findOneAndUpdate() documentation - Detailed API description
- updateOne() documentation - Alternative for simple scenarios