2017-03-16 80 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

相关问题