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 Array element in MongoDB?
Use $addToSet operator to update array element. Let us first create a collection with documents −
> db.updateArrayDemo.insertOne(
... {
...
... "ClientDetails" : [
... {
... "ClientName" : "John",
... "DeveloperDetails" : [ ]
... },
... {
... "ClientName" : "Larry",
... "DeveloperDetails" : [ ]
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccf465edceb9a92e6aa1960")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ccf465edceb9a92e6aa1960"),
"ClientDetails" : [
{
"ClientName" : "John",
"DeveloperDetails" : [ ]
},
{
"ClientName" : "Larry",
"DeveloperDetails" : [ ]
}
]
}
Following is the query to update array element −
> db.updateArrayDemo.update({ "ClientDetails.ClientName": "Larry" },
{ $addToSet: { "ClientDetails.$.Technology": { 'DeveloperName': "Chris", 'WorkExperience':5 } } }, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the array element has been updated or not −
> db.updateArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ccf465edceb9a92e6aa1960"),
"ClientDetails" : [
{
"ClientName" : "John",
"DeveloperDetails" : [ ]
},
{
"ClientName" : "Larry",
"DeveloperDetails" : [ ],
"Technology" : [
{
"DeveloperName" : "Chris",
"WorkExperience" : 5
}
]
}
]
}Advertisements