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