Can MongoDB return result of increment?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 23-May-2019 08:05:25
Advertisements