To increment a field in MongoDB, you can use $inc operator. Let us first create a collection with documents −
> db.incrementDemo.insertOne({"PlayerScore":100});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e")
}
> db.incrementDemo.insertOne({"PlayerScore":290});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc81ce28f9e6ff3eb0ce44f")
}
> db.incrementDemo.insertOne({"PlayerScore":560});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc81ce68f9e6ff3eb0ce450")
}Following is the query to display all documents from a collection with the help of find() method −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 }
{ "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 290 }
{ "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }Following is the query to increment a field in MongoDB −
> db.incrementDemo.update({ _id:ObjectId("5cc81ce28f9e6ff3eb0ce44f") },{ $inc: {"PlayerScore":10 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })In the above query, I have incremented the value 290 with value 10 −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 }
{ "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 }
{ "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }