2011-03-25 70 views
0

这是示例代码:PHP MongoDB的驱动程序,获取数据,然后将其删除,不工作

$r = $coll->findOne(); 
    $coll->remove(array("_id"=>$r["_id"])); // use the same object id as retreived from DB 
    $ret=$coll->findOne(array("_id"=>($r["_id"]))); 
    var_dump($ret); // dumps the records that was supposed to be deleted 

集合中的记录有MongoDB的对象ID,而不是字符串。 控制台上的相同逻辑正常工作并正确删除记录。

回答

2

这是为我工作。下面的代码:

$coll->drop(); 
print("Now have ".$coll->count()." items\n"); 

$coll->insert(array("x" => 'blah')); 
$coll->insert(array("x" => "blahblah")); 
print("Inserted ".$coll->count()." items\n"); 

$x = $coll->findOne(); 
print("Object X\n"); 
print_r($x); 
$query_x = array('_id' => $x['_id']); 
$coll->remove($query_x); 
print("Removed 1 item, now have ".$coll->count()." items\n"); 

$y = $coll->findOne($query_x); 
print("Object Y\n"); 
print_r($y); 

下面是输出:

Now have 0 items 
Inserted 2 items 
Object X 
Array 
(
    [_id] => MongoId Object 
     (
      [$id] => 4d8d124b6803fa623b000000 
     ) 

    [x] => blah 
) 
Removed 1 item, now have 1 items 
Object Y 

你确定有没有一个错字的地方?

0

不同于PHP ==操作符,蒙戈平等操作者始终使用“对象平等”,这是如php的相同比较运算符(===)或Java的.equals()。虽然你的代码看起来应该可以工作(并且它对测试数据集的工作很好),但是关于数据集的一些问题可能会导致PHP将返回的MongoId转换为字符串。 Read more about MongoId here

确保您的查询做查询本身的的var_dump进行比较提供一个MongoId。另外,请确保您正在运行最新版本的PHP Mongo驱动程序。

0

由于PHP是弱类型,以确保你施放的所有输入值和搜索值与预期和一致的数据类型,否则肯定不会找到想要的文档是最重要的。

虽然使用PHP中的MongoDB我使它成为一个点,以避免任何可能的混淆或错误故意施放的一切。

此外,在groups.google.com MongoDB的用户群是非常好的,反应,所以如果你是不是已经利用该资源我肯定会考虑加入它。

相关问题