

- 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
Update a single list item of a MongoDB document?
To update a single list item, use positional operator($). Let us first create a collection with documents −
> db.updateASingleListDemo.insertOne({ _id:1, "EmployeeName":"Chris", "EmployeeDetails": [ {"EmployeeId":"EMP-101","EmployeeSalary": 18999 }] }); { "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateASingleListDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "EmployeeName" : "Chris", "EmployeeDetails" : [ { "EmployeeId" : "EMP-101", "EmployeeSalary" : 18999 } ] }
Following is the query to update a single list item of a MongoDB document. Here, we are updating the salary −
> db.updateASingleListDemo.update({_id: 1, 'EmployeeDetails.EmployeeId': "EMP-101"}, {$inc: {'EmployeeDetails.$.EmployeeSalary': 1}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.updateASingleListDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "EmployeeName" : "Chris", "EmployeeDetails" : [ { "EmployeeId" : "EMP-101", "EmployeeSalary" : 19000 } ] }
- Related Questions & Answers
- Update only a single document in MongoDB
- MongoDB findOneAndUpdate() to update a single document
- Update a single list item of a Mongo DB document and increment it by 1
- Update only a single MongoDB document without deleting any date
- How to update a MongoDB document for adding a new item to an array?
- MongoDB findById returning a list of documents instead of a single result? How to get only a single document?
- How to update the _id of a MongoDB Document?
- Remove only a single document in MongoDB
- MongoDB query to update only a single item from voting (up and down) records?
- Update only a specific value in a MongoDB document
- Increment only a single value in MongoDB document?
- MongoDB query to update a specific document from a collection
- How do you update a MongoDB document while replacing the entire document?
- Update a MongoDB document with Student Id and Name
- Update multiple rows in a single MongoDB query?
Advertisements