如何使用新的php驱动程序库更新mongodb php中的子文档
我正在使用这个php库 我有一个帖子集,在它的一个文档中我添加了多个评论,我可以像这样添加新的评论如何使用新的php驱动程序库更新mongodb php中的子文档,mongodb,mongodb-php,Mongodb,Mongodb Php,我正在使用这个php库 我有一个帖子集,在它的一个文档中我添加了多个评论,我可以像这样添加新的评论 $collection = (new MongoDB\Client)->project->posts; $id = '5799a81fa60afa2010001838'; $result = $collection->updateOne( ["_id" => new MongoDB\BSON\ObjectID($id)], ['$push' =>
$collection = (new MongoDB\Client)->project->posts;
$id = '5799a81fa60afa2010001838';
$result = $collection->updateOne(
["_id" => new MongoDB\BSON\ObjectID($id)],
['$push' => [
"comments" => ['id'=>1,'name' => 'sohss','comm'=>'I like it']
]
]
);
现在,我如何更新我尝试过的任何特定评论,但没有成功
$updateResult = $collection->updateOne(
['_id' => new MongoDB\BSON\ObjectID($id),'comments'],
['$set' =>
['comments'=>[0]=>
['name'=>'123']
]
]
);
更新子文档的正确语法是什么
该文件的结构如下:
{
"_id" : ObjectId("5799a81fa60afa2010001838"),
"title" : "test",
"comments" : [
{
"id" : 3,
"name" : "soh",
"comm" : "I like it"
},
{
"id" : 1,
"name" : "sohss",
"comm" : "I like it"
}
]
}
我们需要使用$positional操作符来更新子文档中的特定字段,例如,如果我想更新id为3的子文档中的名称,我们可以这样做
$updateResult = $collection->updateOne(
['_id' => new MongoDB\BSON\ObjectID($id),'comments.id'=>3],
['$set' =>
['comments.$.name'=> 'Sohail anwar'
]
]
);
您能否显示文档的当前结构以及更新文档的结构以及更新文档的外观?我想更新子文档中的“comm”字段:“I like it”(我喜欢它)如何才能做到这一点