问题
I'm trying to update the value of "position" in "attributes" using the $ set operator with arrayFilters.
The command below works as expected on the terminal
db.produtos.insert(
{
"_id": 1,
"nome":"Nome do Produto",
"descricao":"Lorem ipsum dolor sit amet.",
"atributos": [
{ "id" : 1, "posicao" : 2 },
{ "id" : 2, "posicao" : 1 },
{ "id" : 3, "posicao" : 3 }
]
}
)
db.produtos.update(
{"_id": 1 },
{
$set: {
"atributos.$[elem1].posicao": 1,
"atributos.$[elem2].posicao": 2,
"atributos.$[elem3].posicao": 3
}
},
{
arrayFilters: [
{ "elem1.id": 1 },
{ "elem2.id": 2 },
{ "elem3.id": 3 },
]
}
)
But when I try to create the same command in PHP it does not work.
In my tests, the document is found but never updated.
Just to explain, I get the "attributes.id" of a string, I mount an array with the update and another to filter
<?php
$ids = explode(',', '1,2,3');
$update = [];
$filters = [];
$i = 1;
foreach ($ids as $linha) :
$update['atributos.$[elem'.$i.'].posicao'] = $i;
$filters[]['elem'.$i.'.id'] = $linha;
$i++;
endforeach;
$conexao = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$cmd = new MongoDB\Driver\Command(
[
'findAndModify' => 'produtos',
'query' => ['_id' => 1],
'update' => ['$set' => $update],
'upsert' => true,
'returnDocument' => true,
'new' => true,
'arrayFilters' => $filters,
]
);
$result = $conexao->executeCommand('teste', $cmd)->toArray();
$result = json_decode(json_encode($result), true);
echo '<pre>';
print_r($cmd);
print_r($result);
来源:https://stackoverflow.com/questions/52507129/php-mongodb-set-using-arrayfilters