Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB remove() method is undefined with PHP [closed]

Tags:

php

mongodb

I'm using PHP7 + mongoDB. PHP driver installed with composer.

I have the following code:

<?php
require 'vendor/autoload.php';

$m= new MongoDB\Client("mongodb://127.0.0.1/");

$db = $m->test_database;

$collection = $db->test_table;

$document = array( "first_name" => "Dude", "last_name" => "Dudly" ); 

$collection->insertOne($document);

$cursor = $collection->find();

foreach ($cursor as $document) {
    echo $document["first_name"] . "\n";
}

$collection->remove();
?>

This prints out "Dude" as expected. But also the following exception:

Call to undefined method MongoDB\Collection::remove() in...

And the inserted data in the collection is not removed.

Any idea what's wrong here?

Thanks!

like image 298
SiteAppDev Avatar asked Mar 10 '23 14:03

SiteAppDev


1 Answers

From the docs, remove operation takes query filter for removing documents from collection.

$collection->remove($document, array("justOne" => true));// With filter to remove single entry
$collection->remove(array());//Empty filter will remove all the entries from collection.

Btw you can use newest driver for php http://php.net/manual/en/set.mongodb.php

1: http://php.net/manual/en/mongocollection.remove.php

Update: Didn't realize OP was using composer for MongoDB.

You've to use deleteOne and deleteMany variant with latest driver.

$deleteResult = $collection->deleteOne(["first_name" => "Dude"]);
like image 169
s7vr Avatar answered Mar 12 '23 09:03

s7vr