- Trending Categories
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
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 } ] }
Advertisements