Showing posts with label How to update multiple value of specific embedded document. Show all posts
Showing posts with label How to update multiple value of specific embedded document. Show all posts

Thursday, 9 January 2014

How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?


How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?

MongoDB has a limitation of the same.

for more details please find the below link for your information.

https://jira.mongodb.org/browse/SERVER-1243

for example you have a JSON structure like this ...

{
"_id" : ObjectId("52ce2e4c9109b0e2274a388b"),
"address" : {
"street" : "Aurthor Street 1",
"area" : "Area 1",
"city" : "New York 1",
"country" : "UK"
},
"age" : 29,
"commList" : [
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text",
"date" : ISODate("2014-01-09T05:06:20.283Z")
},
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text 2",
"date" : ISODate("2014-01-09T11:59:57.050Z")
}
],
"commentCount" : 2,
"name" : "Jamse Cook"
}


Now the user name is changed and we need to update the it.

If we try using java code like :

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class, String.class);

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("commList.$.firstName", "Puneet");

WriteResult<Person, String> result = coll.update(DBQuery.is("commList.userId", 1), builder);
System.out.println("rows updated :: " + result.getN());

It updates the first occurence only.

you can use the below code and run it on mongoshell which will update the all occurances
var runUpdate = function(){
db.test.find({"commList.userId" : 1}).forEach( function(test) {
for(var i in test.commList){
test.commList[i].firstName = 'abhijit';
}
db.test.save(test);
});
};

db.eval(runUpdate);