updating embedded array in MongoDB -
i trying update embedded array document in collection structure
{ id: 1, fields:[ { "lang" : "eng","embeddedarray" : ["a","b","c"] }, { "lang" : "abcd","embeddedarray" :["a","d","e"] }] }
i want update in embeddedarray try update using query updating entire array 'a' instead of ['a','b','c']
db.collectionname.update({"fields.embeddedarray" : 'a'}, {"$set" : {"fields.$.embeddedarray" : "a"}});
is way update without loosing other elements in array ?
please check below query :
db.collectionname.find({"fields":{$elemmatch: {"lang":"a"}}}).foreach(function(doc){ var fields = doc.fields; var i,k; for( i=0; i<fields.length; i++ ) { k = fields[i].embeddedarray.indexof("a"); fields[i].embeddedarray.splice(k,1,"a"); } db.collectionname.update({ _id: doc._id},{$set:{"fields": fields}}); });
Comments
Post a Comment