开发者

PHP mongoDb driver , fetching data and then deleting it , is not working

This is the sample code :

  $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

The records in the collection have MongoDB objectId, and not strings. Same logic on console works fine and deleted the record correctly.


This is working for me. Here's the code:

$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);

Here's the output:

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

Are you sure there's not a typo somewhere?


Unlike the php == operator, mongo's equality operator always uses "Object equality" which is like php's identical comparison operator (===) or java's .equals(). While your code looks as though it should work (and it does work fine for me with a test dataset), something about your dataset may be causing php to cast the returned MongoId to a string. Read more about MongoId here.

Make sure that your query is supplying a MongoId for comparison by doing a var_dump of the query itself. Also, make sure that you are running the latest version of the PHP Mongo driver.


Since PHP is loosely typed it is most important to ensure that you cast all input values and search values to the expected and consistent data type otherwise it will surely not locate your expected document.

While using MongoDB within PHP I make it a point to cast everything intentionally in order to avoid any possible confusion or error.

Also, the mongodb-user group at groups.google.com is very good and responsive so if you are not already utilizing that resource I would definitely consider joining it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜