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
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
}
]
}Advertisements