
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 Object at Specific Array Index in MongoDB
To update object at specific array index, use update() in MongoDB. Let us first create a collection with documents −
> db.updateObjectDemo.insertOne( ... { ... id : 101, ... "StudentDetails": ... [ ... [ ... { ... "StudentName": "John" ... }, ... { "StudentName": "Chris" } ... ], ... [ { "StudentName": "Carol" }, ... { "StudentName": "David" } ] ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateObjectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"), "id" : 101, "StudentDetails" : [ [ { "StudentName" : "John" }, { "StudentName" : "Chris" } ], [ { "StudentName" : "Carol" }, { "StudentName" : "David" } ] ] }
Following is the query to update object at specific array index in MongoDB −
> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the object at specific index [1,1]. The value “David” has been updated or not −
> db.updateObjectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"), "id" : 101, "StudentDetails" : [ [ { "StudentName" : "John" }, { "StudentName" : "Chris" } ], [ { "StudentName" : "Carol" }, { "StudentName" : "Mike" } ] ] }
Advertisements