0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Increment Field - Simple Example

Use the $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

Input{ _id: 1 }, increment field 'count' by 1
OutputThe document with _id 1 has its 'count' field increased by 1.
Input{ name: 'Alice' }, increment field 'score' by 5
OutputAll documents with name 'Alice' have their 'score' field increased by 5.
Input{ _id: 2 }, increment field 'visits' by -2
OutputThe document with _id 2 has its 'visits' field decreased by 2.
🧠

How to Think About It

To increment a field in MongoDB, you specify which document(s) to update using a filter, then use the $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

1
Identify the document(s) to update using a filter.
2
Use the $inc operator with the field name and increment value.
3
Run the update query to apply the increment.
4
Check the result to confirm the update.
💻

Code

mongodb
db.users.updateOne({ _id: 1 }, { $inc: { count: 1 } });
print('Incremented count field by 1 for _id 1');
Output
Incremented count field by 1 for _id 1
🔍

Dry Run

Let's trace incrementing the 'count' field by 1 for document with _id 1.

1

Find document

Locate document where _id = 1, e.g., { _id: 1, count: 4 }

2

Apply $inc operator

Add 1 to current count: 4 + 1 = 5

3

Update document

Document becomes { _id: 1, count: 5 }

_idcount BeforeIncrementcount After
1415
💡

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

Using updateMany to increment multiple documents
mongodb
db.users.updateMany({ active: true }, { $inc: { score: 10 } });
print('Incremented score by 10 for all active users');
This increments the field for all documents matching the filter, useful for batch updates.
Using findOneAndUpdate to increment and return updated document
mongodb
const updatedDoc = db.users.findOneAndUpdate(
  { _id: 1 },
  { $inc: { count: 1 } },
  { returnDocument: 'after' }
);
printjson(updatedDoc);
This increments the field and returns the updated document in one operation.

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.

ApproachTimeSpaceBest For
updateOne with $incO(1)O(1)Single document increment
updateMany with $incO(n)O(1)Multiple documents increment
findOneAndUpdate with $incO(1)O(1)Increment and get updated document
💡
Always use $inc to increment numeric fields atomically without overwriting the whole document.
⚠️
Beginners often try to set the field directly instead of using $inc, which overwrites the field instead of incrementing it.