
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Objects in a MongoDB Document's Array
To update the objects in a document’s array, you need to use update() method. To understand the update() method, let us create a collection with document. The query to create a collection with document is as follows:
> db.updateObjects.insertOne({"CustomerId":1,"CustomerName":"Larry","TotalItems":100, ... "ItemDetails":[ ... { ... "NameOfItem":"Item_1", ... "Amount":450 ... }, ... { ... "NameOfItem":"Item_2", ... "Amount":500 ... }, ... { ... "NameOfItem":"Item_3", ... "Amount":200 ... } ... ] ... } ... );
The following is the output:
{ "acknowledged" : true, "insertedId" : ObjectId("5c6d688b0c3d5054b766a769") }
Now you can display documents from a collection with the help of find() method. The query is as follows:
> db.updateObjects.find().pretty();
The following is the output displaying the documents from the collection created above:
{ "_id" : ObjectId("5c6d688b0c3d5054b766a769"), "CustomerId" : 1, "CustomerName" : "Larry", "TotalItems" : 100, "ItemDetails" : [ { "NameOfItem" : "Item_1", "Amount" : 450 }, { "NameOfItem" : "Item_2", "Amount" : 500 }, { "NameOfItem" : "Item_3", "Amount" : 200 } ] }
Increment “Amount”:200 with value 130. The query is as follows. Here, we have used the $inc operator to increment the value of a field:
> db.updateObjects.update({"CustomerId":1,"ItemDetails.NameOfItem":"Item_3"}, {$inc:{"ItemDetails.$.Amount":130}}, ... false,true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
We have successfully updated incremented the value. Let us display the document from the collection. The query is as follows:
> db.updateObjects.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6d688b0c3d5054b766a769"), "CustomerId" : 1, "CustomerName" : "Larry", "TotalItems" : 100, "ItemDetails" : [ { "NameOfItem" : "Item_1", "Amount" : 450 }, { "NameOfItem" : "Item_2", "Amount" : 500 }, { "NameOfItem" : "Item_3", "Amount" : 330 } ] }
Look at the sample output, the Amount 200 is incremented with 130, which is 330 now.