- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Increment only a single value in MongoDB document?
To update only a single value and increment it in MongoDB, use $inc along with update(). Let us create a collection with documents −
> db.demo698.insertOne({Score:78}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398") } > db.demo698.insertOne({Score:56}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8a7551299a9f98c9399") } > db.demo698.insertOne({Score:65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8aa551299a9f98c939a") } > db.demo698.insertOne({Score:88}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8b0551299a9f98c939b") }
Display all documents from a collection with the help of find() method −
> db.demo698.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 } { "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 } { "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 } { "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 88 }
Following is the query to increment only a single value −
> db.demo698.update({_id:ObjectId("5ea6d8b0551299a9f98c939b")},{$inc:{Score:12}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo698.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 } { "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 } { "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 } { "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 100 }
- Related Articles
- Update only a single document in MongoDB
- Remove only a single document in MongoDB
- Retrieve only a single document specifying a criteria in MongoDB?
- Decrement only a single value in MongoDB?
- Update only a specific value in a MongoDB document
- Update only a single MongoDB document without deleting any date
- How to find only a single document satisfying the criteria in MongoDB?
- Increment a field in MongoDB document which is embedded?
- MongoDB findById returning a list of documents instead of a single result? How to get only a single document?
- MongoDB findOneAndUpdate() to update a single document
- Increment a value in a MongoDB nested object?
- Remove only one document in MongoDB?
- Increment MongoDB value inside a nested array
- Update a single list item of a MongoDB document?
- Updating a MongoDB document and adding new keys only in the first document?

Advertisements