incrementOne() - Atomic increment/decrement field value
Method overview
incrementOne is a convenience method for atomically incrementing or decrementing a field value in a single document, simplifying the use of updateOne({ $inc }).
Why is incrementOne needed?
Traditional way (using updateOne):
Use incrementOne:
Core Advantages
Method signature
Parameter description
Basic example
Example 1: Increment (default +1)
Example 2: Specify increment
Example 3: Decrement (negative number)
Example 4: Simultaneous operation of multiple fields
Example 5: Return updated document
Real scene example
Scenario 1: Statistics of login times
Scenario 2: Points System
Scenario 3: Article views
Scenario 4: Inventory Management
Scenario 5: Multi-dimensional statistics
Detailed explanation of option parameters
returnDocument - return timing
projection - field projection
Performance Notes
Atomic guarantee
incrementOne uses MongoDB’s $inc operator to ensure atomicity:
- ✅ Concurrency safety
- ✅ No race conditions
- ✅ No transactions required
Performance comparison
Error handling
Error type
Error handling example
Best Practices
✅ Recommended practices
-
Use incrementOne instead of find + update
-
Check return value
❌ Things to avoid
- Avoid using in loops
Compare with other methods
vs updateOne({ $inc })
FAQ
Q1: What is the difference between incrementOne and updateOne?
A: incrementOne is a convenience method of updateOne({ $inc }), with clearer semantics and simpler code.
Q2: Does it support concurrency?
A: ✅ Yes! incrementOne is an atomic operation and is concurrency safe.
Q3: Can it be reduced?
A: ✅ Yes! Just use negative numbers:
Q4: What happens when the field does not exist?
A: MongoDB will automatically create fields, starting from 0 and increasing.
Q5: How to operate multiple fields at the same time?
A: Use object form:
See also
- updateOne() - Update a single document
- findOneAndUpdate() - Find and update
- upsertOne() - Update if it exists, insert if it does not exist
- MongoDB official documentation: $inc operator