

- 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 elements inside an array in MongoDB?
To update elements inside an array, use $set in MongoDB. Let us create a collection with documents −
> db.demo494.insertOne( ... { ... ... "CollegeDetails" : [ ... { ... "CollegeName" : "MIT", ... "Fees" : 80000 ... }, ... { ... "CollegeName" : "SU", ... "Fees" : 90000 ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e84a5c1b0f3fa88e22790c9") }
Display all documents from a collection with the help of find() method −
> db.demo494.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"), "CollegeDetails" : [ { "CollegeName" : "MIT", "Fees" : 80000 }, { "CollegeName" : "SU", "Fees" : 90000 } ] }
Following is the query to update elements inside an array in MongoDB −
> db.demo494.update( ... ... { ... "CollegeDetails.CollegeName": "MIT" ... }, ... ... { ... $set: ... { ... "CollegeDetails.$.Fees" : 100000 ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo494.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"), "CollegeDetails" : [ { "CollegeName" : "MIT", "Fees" : 100000 }, { "CollegeName" : "SU", "Fees" : 90000 } ] }
- Related Questions & Answers
- Update multiple elements in an array in MongoDB?
- Perform multiple updates with bulk operations and update elements in an array in MongoDB
- Match multiple criteria inside an array with MongoDB?
- MongoDB query to update an array using FindAndUpdate()?
- Update Array element in MongoDB?
- How to increment inside the update() function in MongoDB?
- Update an array of strings nested within an array of objects in MongoDB
- MongoDB query to find data from an array inside an object?
- MongoDB Aggregation to slice array inside array
- How to match multiple criteria inside an array with MongoDB?
- How to get the matching document inside an array in MongoDB?
- MongoDB Increment value inside nested array?
- MongoDB aggregation with equality inside array?
- MongoDB syntax for updating an object inside an array within a document?
- How to merge specific elements inside an array together - JavaScript
Advertisements