To update specific records of an array field in MongoDB, we can achieve that by using JavaScript with Mongo query. Below are the two ways to update the arrays. Lets see both ways to update the data.
Employee Collection:
Objective is to update above array's joineddate field where department is finance.
Option 1: Updating the array using JavaScript:
Option 2: Updating array using Mongo Query operators update and set:
Employee Collection:
{
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"profile":[ {"department" : "finance", "joineddate" : "2010-04-10"},
{"department" : "marketing", "joineddate" : "2008-05-05"},
{"department" : "hr", "joineddate" : "2006-08-05"}
]
},
{
"_id" : 2,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"profile":[ {"department" : "retail", "joineddate" : "2013-07-10"},
{"department" : "finance", "joineddate" : "2010-05-25"},
{"department" : "hr", "joineddate" : "2007-08-05"}
]
}
Objective is to update above array's joineddate field where department is finance.
Option 1: Updating the array using JavaScript:
db.employee.find({}).
forEach(function(doc){
doc.profile.forEach(function(d){
if(d.department == "finance")
{
d.joineddate = "2016-12-12"
}
});
db.employee.save(doc);
})
Option 2: Updating array using Mongo Query operators update and set:
var query = {
profile: {
$elemMatch: {
department: "finance",
joineddate: {$ne: "2016-12-12"}
}
}
};
while (db.employee.find(query).count() > 0) {
db.employee.update(
query,
{ $set: { "profile.$.joineddate": "2016-12-12" } },
{ multi: true }
);
}