Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: trueoption 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.
Advertisements
