2017-03-16 79 views
2

我正在使用PHP7 + mongoDB。安裝了作曲家的PHP驅動程序。MongoDB remove()方法未定義,使用PHP

我有以下代碼:

<?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(); 
?> 

這種打印出 「哥們」 預期。 但也以下異常:

調用未定義的方法的MongoDB \收藏::刪除()在...

和收集中所插入的數據不會被刪除。

任何想法這裏有什麼問題嗎?

謝謝!

+1

如果您使用[這](https://github.com/mongodb/mongo-php-library/blob/master/src/Collection.php)庫,那麼,'Collection'確沒有'remove'方法。你爲什麼認爲它應該?它應該做什麼? – deceze

回答

1

docs,remove操作需要查詢過濾器用於從集合中刪除文檔。

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

順便說一句,你可以使用最新的驅動程序,PHP http://php.net/manual/en/set.mongodb.php

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

更新:OP用作曲家的MongoDB沒有意識到。

你必須使用deleteOnedeleteMany變種與最新的驅動程序。

$deleteResult = $collection->deleteOne(["first_name" => "Dude"]); 
+0

謝謝!真棒回答,你拯救我的一天! – user79382

相關問題