2016-08-02 61 views
2

更新MongoDB的PHP的子文件我使用這個PHP libarary http://mongodb.github.io/mongo-php-library/如何使用新的PHP驅動程序庫

我有一個集合的帖子和一個文檔中我加入多條評論,我可以像下面這樣添加新的評論

$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" 
    } 
    ] 
} 
+0

您可以顯示文檔的當前結構以及更新文檔的結構 – Webdev

+0

更新文檔的外觀應該如何? – Webdev

+0

我想在子文件中更新「comm」字段:「我喜歡它」我該怎麼做 –

回答

0

我們需要使用$位置操作,以更新子文檔如特定領域,如果我想在ID 3,我們可以在子文檔更新名稱像這樣做

$updateResult = $collection->updateOne(
       ['_id' => new MongoDB\BSON\ObjectID($id),'comments.id'=>3], 
       ['$set' => 
          ['comments.$.name'=> 'Sohail anwar' 

          ] 
       ] 
      ); 
相關問題