Let's say I have some documents of such type:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134
},
{
a: 2,
b: "aaa",
c: 564
}
]
}
What I need to do is to update all the obj_array elements by pushing a new field d: "new_value". Expected result:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134,
d: "new_value"
},
{
a: 2,
b: "aaa",
c: 564,
d: "new_value"
}
]
}
I didn't find any other solution but constructing new obj_array object and setting doc.obj_array with the new array. I wonder is there some more elegant way to do that?
Here's my code:
myTable.find().forEach(function(document) {
var new_array = [];
document.obj_array.forEach(function(elem) {
elem.d = "new_value";
new_array.push(elem);
})
myTable.update({_id: document._id}, {$set: {obj_array: new_array}})
})