- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB syntax for updating an object inside an array within a document?
For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.
Let us create a collection with documents −
> db.demo553.insertOne( ... { ... id:101, ... "Name":"John", ... midExamDetails: ... [ ... {"SubjectName":"MySQL","Marks":70}, ... {"SubjectName":"MongoDB","Marks":35} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8e3da19e5f92834d7f05ed") }
Display all documents from a collection with the help of find() method −
> db.demo553.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 35 } ] }
Following is the query to the syntax for updating an object inside an array within a MongoDB document −
> db.demo553.findOneAndUpdate( ... { id:101, ... "midExamDetails.SubjectName":"MongoDB" ... }, ... { $set:{ ... 'midExamDetails.$.Marks': 97 ... } ... } ... ); { "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 35 } ] }
Display all documents from a collection with the help of find() method −
> db.demo553.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [ { "SubjectName" : "MySQL", "Marks" : 70 }, { "SubjectName" : "MongoDB", "Marks" : 97 } ] }
- Related Articles
- How to get the matching document inside an array in MongoDB?
- MongoDB query to find data from an array inside an object?
- How to project specific fields from a document inside an array in Mongodb?
- Updating an array with $push in MongoDB
- Get array items inside a MongoDB document?
- Updating nested document in MongoDB
- How to insert an item to an array that is inside an object in MongoDB?
- How to get a specific object from array of objects inside specific MongoDB document?
- How to push new items to an array inside of an object in MongoDB?
- MongoDB query for Partial Object in an array
- Query a nested field within an array with MongoDB
- Update elements inside an array in MongoDB?
- How to update a MongoDB document for adding a new item to an array?
- Add a field to an embedded document in an array in MongoDB?
- MongoDB query to push document into an array

Advertisements