Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to update only a single item from voting (up and down) records?
To update a single field in MongoDB voting records, use the $inc operator to increment or decrement vote counts. This allows you to modify only the TotalVote field without affecting other document properties.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $inc: { "fieldToUpdate": incrementValue } }
);
Create Sample Data
Let us first create a collection with voting records ?
db.demo57.insertMany([
{ "Votes": { "VoterName": "Chris", "TotalVote": 50 } },
{ "Votes": { "VoterName": "David", "TotalVote": 101 } }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e285bb8cfb11e5c34d8991a"),
ObjectId("5e285bc3cfb11e5c34d8991b")
]
}
Display all documents from the collection ?
db.demo57.find();
{ "_id": ObjectId("5e285bb8cfb11e5c34d8991a"), "Votes": { "VoterName": "Chris", "TotalVote": 50 } }
{ "_id": ObjectId("5e285bc3cfb11e5c34d8991b"), "Votes": { "VoterName": "David", "TotalVote": 101 } }
Example: Update Single Vote Count
Here is the query to update only David's TotalVote by incrementing it by 19 ?
db.demo57.update(
{ "Votes.VoterName": "David" },
{ $inc: { "Votes.TotalVote": 19 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated documents ?
db.demo57.find();
{ "_id": ObjectId("5e285bb8cfb11e5c34d8991a"), "Votes": { "VoterName": "Chris", "TotalVote": 50 } }
{ "_id": ObjectId("5e285bc3cfb11e5c34d8991b"), "Votes": { "VoterName": "David", "TotalVote": 120 } }
Key Points
- Use
$incwith positive values for upvotes and negative values for downvotes - Dot notation targets nested fields like
"Votes.TotalVote" - Only the specified field is modified; other document properties remain unchanged
Conclusion
The $inc operator efficiently updates single voting fields by incrementing or decrementing values. This approach ensures atomic updates while preserving the integrity of other document data.
Advertisements
