Skip to content
Advertisement

How can I filter a MongoDB entry to update it using updateOne on PHP?

I am trying to update an entry on MongoDB using the code below. I want it so that it updates the ‘name’ field pertaining to the studentid posted from the html form. I keep getting a syntax error for unexpected ) even though I have changed it around a lot to no avail. I got this code straight from the MongoDB documentation too?

<?php
require 'vendor/autoload.php' ;
$client = new MongoDBClient('mongodb://127.0.0.1:27017');
$db_name = 'studentsinfo';
$db = $client->$db_name;
$collection = $db->students;

if($_POST)
{
  $update = $collection->updateOne([
  'studentid'=> $_POST['studentid'],
   [ '$set' => [ 'name' => 'Brunos on Astoria' ]]
  
);
}

Advertisement

Answer

Missing square bracket ] in your updateOne method:

if($_POST){
     $update = $collection->updateOne(
     ['studentid'=> $_POST['studentid']],
     [ '$set' => [ 'name' => 'Brunos on Astoria' ]]
     );
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement