I am trying to delete a sub document from a collection. I have tried below lines of code
public function deleteContactDetailsForItsSubDocument()
{
$this->collection->updateOne(
array('_id' => new MongoDB\BSON\ObjectID($this->id)),
array('$pull' =>
array('ContactDetails.ContactTypeId' => $this->ContactTypeId)
));
}
It throw error message "Uncaught exception 'MongoDB\Driver\Exception\BulkWriteException' with message 'Cannot use the part (ContactTypeId) of (ContactDetails.ContactTypeId) to traverse the element"
The document in collection is like
{
"_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"
}
]
...
Try this:
$this->collection->updateOne(
array('_id' => new MongoDB\BSON\ObjectID($this->id)),
array('$pull' =>
array('ContactDetails' =>
array('ContactTypeId' => $this->ContactTypeId)
)
)
);