Update nested child elements with jenssegers/laravel-mongodb

601 views Asked by At

I have a document with child elements of items like so

"bar" : "d bar",
"items" : [ 
        {       
            "message" : "one",
            "display" : "true",
            "type" : "text"     
        } 
        {       
            "message" : "one2",
            "display" : "true",
            "type" : "text2"     
        }
        {       
            "message" : "one2",
            "display" : "false",
            "type" : "text3"     
        }
]

I want to update the fields that are 'one2' in the array to 'one22'. I'm writing this command, but it only updates the first value.

Bars::where('bar', 'd bar')
    ->where('items.message', 'one2')
    ->update(['items.$.message' => 'one22']);
2

There are 2 answers

3
Ben0n On

It's a little late, but maybe the answer will help others.

If you change your query just a little it should work:

Bars::where('bar', 'd bar')
    ->where('items.message', 'one2')
    ->update(['items.$[].message' => 'one22']);

From MongoDB Docs:

  • $ Acts as a placeholder to update the first element that matches the query condition.
  • $[] Acts as a placeholder to update all elements in an array for the documents that match the query condition.
0
Amit Shah On

Not sure for the multidimensional array as above, but if this can be done on single dimension array as below then should work for 2nd level too.

My workaround solution for Laravel.MongoDB:

$user = Player::firstOrCreate(['email' => strtolower($email)]);
$user->items = array_merge( (array) $user->items ?? [], ['key'=>'val']);

This will create items attribute if not exists or append in existing.