

- 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
MongoDB query to update array object in index N?
Use update() in MongoDB to update array object. The usage of dot notation is also required. Let us create a collection with documents −
> db.demo489.insertOne( ... { ... ... ... details : [{ ... id : 101, ... "Info1" : { ... "StudentName" : "Chris" ... }, ... "Info2" : { ... "TeacherName" : "David" ... } ... }, ... { ... id : 102, ... "Info1" : { ... "StudentName" : "Carol" ... }, ... "Info2" : { ... "TeacherName" : "Mike" ... } ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8356e0b0f3fa88e22790ba") }
Display all documents from a collection with the help of find() method −
> db.demo489.find();
This will produce the following output −
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : { "StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : { "StudentName" : "Carol" }, "Info2" : { "TeacherName" : "Mike" } } ] }
Following is the query to update array object −
> db.demo489.update({"details.id":102}, ... {$set: {"details.$.Info1.StudentName":"Robert", ... "details.$.Info2.TeacherName":"John", ... "details.$.CountryName" : "US" ... ... } ... }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo489.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : { "StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : { "StudentName" : "Robert" }, "Info2" : { "TeacherName" : "John" }, "CountryName" : "US" } ] }
- Related Questions & Answers
- Update object at specific Array Index in MongoDB?
- Update array in MongoDB document by variable index?
- Query Array for 'true' value at index n in MongoDB?
- MongoDB query to update an array using FindAndUpdate()?
- MongoDB query to update array with another field?
- MongoDB query to update tag
- How to update MongoDB Object?
- MongoDB query to update selected fields
- MongoDB query to update nested document
- MongoDB query to access an object in an array
- MongoDB query for Partial Object in an array
- Update object in array with a specific key in MongoDB
- MongoDB query to remove empty objects in an object-array?
- MongoDB query to update only certain fields?
- MongoDB query to update the nested document?
Advertisements