I am trying to update subdocument array in PHP Mongo
$result = $collection->updateMany(
[
'_id' => new MongoDB\BSON\ObjectID('61613dcd437b996bc227ffe2'),
'messages.type' => 'test'
],
['$set' => ['messages.$[m].direction' => '999']],
[
'multi' => true,
'arrayFilters' => [['m.type'=> 'test']]
]
);
####Update . My array is
[{"_id":{"$oid":"6163f2c9fc197a54f03ca8c8"},"id":7,},"messages":{"1":{"type":"1","time":"19.04.2020 09:14:42","message":"This is testmsg"}},"ssg":"ruther"}]
Also, How Can I update whole sub-document with indexes1,2,3.. so on ?
use $[]
and arrayFilters
db.collection.update({
"_id": ObjectId("61603458c08ad41af13bf352"),
"messages.type": "05.04.2020 03:27:23"
},
{
$set: {
"messages.$[m].direction": "999"
}
},
{
multi: true,
arrayFilters: [
{
"m.type": "05.04.2020 03:27:23"
}
]
})
Update
If you want to replace that single Message array with the new one
$set: {
"messages.$[m]": {
"type": "02.06.2020 19:27:23",
"message": "This is a 3 Msg",
"direction": "0"
}
}