在mongo db php中更新特定的子文档

时间:2018-02-21 18:36:11

标签: mongodb mongodb-php php-mongodb

我在mongo db中有一个名为EmployeeTbl的集合,其文档类似于

{
"_id": ObjectId("5a8d47d8d2ccda11fc004d91"),
"EmployeeNumber": "9883456787",
"FirstName": "Sana",
 ...
  "ContactDetails": [
 {
   "ContactTypeId": "04596c6f-82e6-8f00-e3a9-1f3199894284",
   "ContactType": "Phone",
   "ContactTypeValue": "99456789756" 
},
 {
   "ContactTypeId": "71d0152c-293f-4c6f-2360-bbdfe368eacb",
   "ContactType": "Phone",
   "ContactTypeValue": "9894567890" 
  } 
 ] 

}

我正在尝试更新ContactDetails中的子文档,我已经编写了下面的代码。它没有更新现有的。它不是更新,而是添加新的子文档。 请帮帮我!!!

     public function updateContactDetailsForItsSubDocument()
{
             // $bulkbatch = new MongoDB\Driver\BulkWrite(['ordered' => true]);  

              $subDocumentContactDetails = array(
                            "ContactDetails" => 
                                      array(
                                      "ContactType" => $this->ContactType,
                                      "ContactTypeValue" => $this->ContactTypeValue
                                   )
                               );

              $this->collection->update(
                            array('_id' => new MongoDB\BSON\ObjectID($this->id), 'ContactDetails.ContactTypeId'=> $this->ContactTypeId),
                            array('$set' => $subDocumentContactDetails)
                                );

             // $this->manager->executeBulkWrite($this->collection, $bulkbatch);  

}

1 个答案:

答案 0 :(得分:1)

更改您的$subDocumentContactDetails变量,以便它使用$ positional operator更新嵌入文档:

$subDocumentContactDetails = array(
    "ContactDetails.$.ContactType" => $this->ContactType,
    "ContactDetails.$.ContactTypeValue" => $this->ContactTypeValue
);

$this->collection->update(
    array(
        "_id" => new MongoDB\BSON\ObjectID($this->id), 
        "ContactDetails.ContactTypeId" => $this->ContactTypeId
    ),
    array("$set" => $subDocumentContactDetails)
);