MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - PHP - Deleting a Document



MongoDB provides MongoCollection class to delete a document in a collection.

Syntax

// select a collection
$collection = $db->mycol;

// now delete the document
$collection->deleteOne(array("title"=>"MongoDB Tutorial"));
echo "<br/>Document deleted successfully.<br/>";
	
// now try to display the document
$cursor = $collection->find();
	
foreach ($cursor as $document) {
   echo $document["title"] . "<br/>";
}

Deleting Document from a Collection

To update a document, we first need to connect to a database and then select the collection and then delete the document as shown below −

<?php
   require __DIR__ . '\vendor\autoload.php';
   try {
	  $uri = "mongodb://localhost:27017";
      // connect to mongodb
      $client = new MongoDB\Client($uri);
      echo "Connection to database successful.";
       // select a database
      $db = $client->myDb;
      echo "<br/>Database myDb selected.";
      $collection = $db->mycol;
      echo "<br/>Collection selected succsessfully.";

      // select a collection
      $collection = $db->mycol;

      // now delete the document
      $collection->deleteOne(array("title"=>"MongoDB Tutorial"));
      echo "<br/>Document deleted successfully.<br/>";
	
      // now try to display the document
      $cursor = $collection->find();
	
      foreach ($cursor as $document) {
         echo $document["title"] . "<br/>";
      }
	  	  
   } catch (MongoDB\Driver\Exception\Exception $e) {	   
      echo "Exception:", $e->getMessage(), "\n";
   }
?>

Output

Now, let's compile and run the above program to delete a document from a collection in our database myDb.

On executing, the above program gives you the following output.

Connection to database successful.
Database myDb selected.
Collection selected succsessfully.
Document deleted successfully.
Advertisements