![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } }
Advertisements