0

I have the following document:

{
   _id: objectId("5aa7abb3c7dc133b0007e6e"),
   name: "first course",
   targets: Array
     0: Object
        id: "11111_rrrr",
        value: "test"
     1: Object
        id: "22222_rrrr",
        value: "hi"
}

so, I want to change the value of the array[i]. my solution is :

$update = array(
        'targets.$[].value' => "New Value"
    );

    $result = Course::where("_id", $course_id)->update($update);

it changes all the value of the array, how can I solve my problem??

Mohammad Bitar
  • 48
  • 1
  • 10
  • Use `$update = array( 'targets.0.value' => "New Value" );` – s7vr Mar 14 '18 at 13:40
  • 1
    I have dashboard so, I don't know any index in the array. I need a dynamic way to iterate the array. – Mohammad Bitar Mar 14 '18 at 13:42
  • You said _so, all I want to do is to change the value of the array[0]_ – s7vr Mar 14 '18 at 13:43
  • I'm sorry, I will change my question. – Mohammad Bitar Mar 14 '18 at 13:45
  • Dont be sorry. Its fine. So how do you identify the array. is it by id ? – s7vr Mar 14 '18 at 13:46
  • yes, my document is like this : "_id" : ObjectId("5aa7abb3c7dc1c33b00076e6"), "name" : "first_coursetest", "caption" : "First Course", "targets" : [ { "id" : "1520937903756_", "value" : "qqq", }, { "id" : "1521028321828_as", "value" : "qqq", } ] – Mohammad Bitar Mar 14 '18 at 13:46
  • and I have target_id, but I can't make a condition between $target_id and id inside the array – Mohammad Bitar Mar 14 '18 at 13:51
  • Try `Course::raw()->findOneAndUpdate( ['_id' => $user_id, 'targets.id' => $target_id], ['$set' => ["targets.$.value" => "New Value"]] );` – s7vr Mar 14 '18 at 13:54
  • @Veeram thanks, bro it works for me I was trying to use update not findoneandupdate so is there any place I can revise the pipeline stages for laravel jenssegers – Mohammad Bitar Mar 14 '18 at 14:15
  • Np. I'm not sure but try `$update = array( 'targets.$.value' => "New Value" );$result = Course::where(['_id' => $user_id, 'targets.id' => $target_id])->update($update);` – s7vr Mar 14 '18 at 14:39
  • Ok, my problem solved. Thank you very much for your response. – Mohammad Bitar Mar 14 '18 at 14:53

1 Answers1

0

Try this

db.getCollection('TEST').update({"targets.id" : $course_id},{$set:{"targets.$.value" : "New Value"}})
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37