phpmongodbmongomapperdatabase

mongodb remove does not return boolean


I have been playing with mongodb for a while. I dont get the concept that when I try to remove a non-existing value or key it does not gives me an error.

        $host = '10.311.33.2';
        $user = 'admin'; $password = 'admin';
        tmpHost ="mongodb://$user:$password@$host";
        $m = new Mongo("$tmpHost");
        $db = $m->selectDB("common");
        $collection = new MongoCollection($db,"list");
        $result = array('name'=>'ali');
        $collection->insert($result);
        if($collection->remove($result)){
        echo "Remove";}
        else{
         echo "Not removed";}
        // Should display Not removed, since its not existing. but it displays Remove :S
        if($collection->remove($result)){
        echo "Remove";}
        else{
         echo "Not removed";}

How can such db be used,


Solution

  • You are calling MongoCollection::remove without the safe flag in the options (you are calling it without any options). That means the command behaves in a fire-and-forget manner. It is sent to the database and program execution continues without waiting for a reply.

    When you call it like that:

    $collection->remove($result, array("safe" => true))
    

    the return value will be an array which contains information about how the query worked. The field "n" of this array contains the number of affected objects. When the remove command did nothing, this should be 0.

    By the way: Most databases I worked with before do not treat a deletion query which doesn't affect anything as an error.