Home > database >  How can i update an element of a subarray in a mongodb document with php?
How can i update an element of a subarray in a mongodb document with php?

Time:01-10

Suppose we have the following document stored in our mongodb :

{
  "_id": {
    "$oid": "63bc85eef11800007e004a78"
  },
  "username": "test",
  "email": "[email protected]",
  "password": "password123",
  "gender": "Male",
  "age": "44",
  "plan": "free",
  "loggedIn": "2023-01-09 22:47:06",
  "loggedOut": "2023-01-09 22:47:26"
  "products": [
    "apples",
    "watermelon"
  ]
}

Being connected to the db, i want with php to change the value of "apples" to lets say "orange". How can I achieve this?

When i wanted to delete lets say "apples", i would do the following :

$productName = "apples";
$filter = array('email'=>$user['email']);
$delete = array( '$pull' =>array("products" =>$productName));
$queryDelete->updateOne($filter,$delete);

And it would work. But I can't seem to be able to do the same with updating the value "apples" to "orange".

CodePudding user response:

To update the array in a document, try the following code.

    // Specify the filter to select the document
    $filter = ['_id' => new MongoDB\BSON\ObjectId('63bc85eef11800007e004a78')];
    
    // Specify the update operations to be performed.
    // You need to get the index of apples from the array.
    $update = ['$set' => ['products.0' => 'new value']];
    
    // Update the document
    $result = $collection->updateOne($filter, $update);
  • Related