

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 } }
- Related Questions & Answers
- Update only a single document in MongoDB
- Update a single list item of a MongoDB document?
- MySQL update multiple records in a single query?
- MongoDB query to update only certain fields?
- Update multiple rows in a single MongoDB query?
- MongoDB query to update a MongoDB row with only the objectid
- A single MySQL query to update only specific records in a range without updating the entire column
- MongoDB query to remove item from array?
- Selecting only a single field from MongoDB?
- MongoDB query to search date records using only Month and Day
- Update only a single MongoDB document without deleting any date
- MySQL query to update only a single field in place of NULL
- MongoDB Query to search for records only in a specific hour?
- How to run MongoDB query to update only a specific field value?
- MySQL query to display only the records that contains single word?
Advertisements