Can MongoDB return result of increment?

Yes, MongoDB can return the result of an increment operation using the findAndModify() method. This allows you to atomically increment a value and retrieve the updated document in a single operation.

Syntax

db.collection.findAndModify({
    query: { /* match criteria */ },
    update: { $inc: { "field": incrementValue } },
    new: true
});

Sample Data

Let us first create a collection with a sample document:

db.returnResultOfIncementDemo.insertOne({"PlayerScore": 98});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd3c292edc6604c74817cda")
}

Display the document to verify:

db.returnResultOfIncementDemo.find();
{ "_id": ObjectId("5cd3c292edc6604c74817cda"), "PlayerScore": 98 }

Example: Increment and Return Result

The following query increments PlayerScore by 2 and returns the updated document:

db.returnResultOfIncementDemo.findAndModify({
    query: {},
    update: { $inc: {PlayerScore: 2} },
    new: true
});
{ "_id": ObjectId("5cd3c292edc6604c74817cda"), "PlayerScore": 100 }

Key Points

  • The new: true option returns the modified document (after increment).
  • Without new: true, it returns the original document (before increment).
  • The operation is atomic, ensuring thread-safe increment and retrieval.

Conclusion

Use findAndModify() with $inc and new: true to atomically increment values and return the updated result. This method is essential for scenarios requiring both increment and immediate access to the new value.

Updated on: 2026-03-15T01:08:31+05:30

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements