Can MongoDB return result of increment?


Yes, you can achieve this with findAndModify(). Let us first create a collection with documents −

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

Following is the query to display all documents from a collection with the help of find() method −

> db.returnResultOfIncementDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd3c292edc6604c74817cda"), "PlayerScore" : 98 }

Following is the query to return result of increment. Here, we have incremented PlayerScore by 2 −

> db.returnResultOfIncementDemo.findAndModify({
...   query:{},
...   update: { $inc: {PlayerScore: 2 }},
...   new: true
... });

This will produce the following output −

{ "_id" : ObjectId("5cd3c292edc6604c74817cda"), "PlayerScore" : 100 }

Updated on: 30-Jul-2019

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements