MongoDB Query to Increment Field - Simple Example
$inc operator in an updateOne or updateMany query to increment a field, for example: db.collection.updateOne({filter}, {$inc: {field: 1}}) increments the field by 1.Examples
How to Think About It
$inc operator with the field name and the amount to add. MongoDB will add that number to the current value of the field, creating the field if it doesn't exist.Algorithm
Code
db.users.updateOne({ _id: 1 }, { $inc: { count: 1 } });
print('Incremented count field by 1 for _id 1');Dry Run
Let's trace incrementing the 'count' field by 1 for document with _id 1.
Find document
Locate document where _id = 1, e.g., { _id: 1, count: 4 }
Apply $inc operator
Add 1 to current count: 4 + 1 = 5
Update document
Document becomes { _id: 1, count: 5 }
| _id | count Before | Increment | count After |
|---|---|---|---|
| 1 | 4 | 1 | 5 |
Why This Works
Step 1: Use of $inc operator
The $inc operator tells MongoDB to add a specified value to a field atomically.
Step 2: Filter selects document(s)
The filter part of the query finds which document(s) to update, for example by _id or other criteria.
Step 3: Field creation if missing
If the field does not exist, MongoDB creates it and sets it to the increment value.
Alternative Approaches
db.users.updateMany({ active: true }, { $inc: { score: 10 } });
print('Incremented score by 10 for all active users');const updatedDoc = db.users.findOneAndUpdate( { _id: 1 }, { $inc: { count: 1 } }, { returnDocument: 'after' } ); printjson(updatedDoc);
Complexity: O(1) time, O(1) space
Time Complexity
Incrementing a field uses an index or direct document access, so it runs in constant time relative to the document size.
Space Complexity
The operation modifies the document in place, requiring no extra space beyond the update command.
Which Approach is Fastest?
Using updateOne with $inc is fastest for single documents; updateMany is efficient for batch increments.
| Approach | Time | Space | Best For |
|---|---|---|---|
| updateOne with $inc | O(1) | O(1) | Single document increment |
| updateMany with $inc | O(n) | O(1) | Multiple documents increment |
| findOneAndUpdate with $inc | O(1) | O(1) | Increment and get updated document |
$inc to increment numeric fields atomically without overwriting the whole document.$inc, which overwrites the field instead of incrementing it.