Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push field to each element of object array (MongoDB)

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}})
})
like image 201
anako Avatar asked Dec 16 '25 19:12

anako


2 Answers

You can use $[] the all positional operator which updates all the elements in an array

myTable.update(
  { "_id": document._id },
  { "$set": { "obj_array.$[].d": "new_value" }}
)
like image 55
Ashh Avatar answered Dec 19 '25 08:12

Ashh


You can simply achieve this by traverse array through $[] and update it:

for single update:

db.getCollection('test').update({},{ "$set": { "array.$[].key": "Value" }})

multiple updates:

db.getCollection('test').updateMany({},{ "$set": { "array.$[].key": "Value" }})

like image 24
Neel Rathod Avatar answered Dec 19 '25 08:12

Neel Rathod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!