0

这是示例代码:

  $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 objectId,而不是字符串。控制台上的相同逻辑工作正常并正确删除了记录。

4

3 回答 3

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

你确定哪里没有错字吗?

于 2011-03-25T22:10:43.260 回答
0

与 php == 运算符不同,mongo 的相等运算符总是使用“对象相等”,这类似于 php 的相同比较运算符 (===) 或 java 的 .equals()。虽然您的代码看起来应该可以工作(并且它对我来说使用测试数据集确实可以正常工作),但关于您的数据集的某些内容可能会导致 php 将返回的 MongoId 转换为字符串。 在此处阅读有关 MongoId 的更多信息

通过执行查询本身的 var_dump 确保您的查询提供了 MongoId 进行比较。此外,请确保您运行的是最新版本的 PHP Mongo 驱动程序。

于 2011-03-26T14:12:18.973 回答
0

由于 PHP 是松散类型的,因此最重要的是确保将所有输入值和搜索值转换为预期且一致的数据类型,否则它肯定无法找到预期的文档。

在 PHP 中使用 MongoDB 时,我会故意强制转换所有内容,以避免任何可能的混淆或错误。

此外,groups.google.com 上的 mongodb-user 组非常好且响应迅速,因此如果您还没有使用该资源,我肯定会考虑加入它。

于 2011-06-06T20:54:26.040 回答