MongoDB query to update only a single item from voting (up and down) records?


Let us first create a collection with documents −

> db.demo57.insertOne({"Votes":{"VoterName":"Chris","TotalVote":50}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285bb8cfb11e5c34d8991a")
}
> db.demo57.insertOne({"Votes":{"VoterName":"David","TotalVote":101}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285bc3cfb11e5c34d8991b")
}

Display all documents from a collection with the help of find() method −

> db.demo57.find();

This will produce the following output −

{ "_id" : ObjectId("5e285bb8cfb11e5c34d8991a"), "Votes" : { "VoterName" : "Chris", "TotalVote" : 50 } }
{ "_id" : ObjectId("5e285bc3cfb11e5c34d8991b"), "Votes" : { "VoterName" : "David", "TotalVote" : 101 } }

Here is the query to update only a single item (TotalVote) −

> db.demo57.update({"Votes.VoterName":"David" },{ $inc : { "Votes.TotalVote" : 19 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo57.find();

This will produce the following output −

{ "_id" : ObjectId("5e285bb8cfb11e5c34d8991a"), "Votes" : { "VoterName" : "Chris", "TotalVote" : 50 } }
{ "_id" : ObjectId("5e285bc3cfb11e5c34d8991b"), "Votes" : { "VoterName" : "David", "TotalVote" : 120 } }

Updated on: 03-Apr-2020

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements