phpmongodbphp-mongodbobject-identity

mongoDB wont allow me to update


Ok this issue is driving me nutts, I thought that _id was meant to be ObjectID while the first time it inserts it does it correctly when I try to update it using the _id it does not work.

here is my code

//Save Data
    function savedata($data){
        $collection = $this->db->retail_logs;
        $this->data = $data;

        if($this->data['_id'] == NULL || $this->data['_id'] == "")
        {
            $this->data['_id'] = new MongoId();
        }
        else
        {
         $this->data['_id'] = ObjectID($this->data['_id']);
        }   
        try {
        $collection->update(
            array("_id"=>$this->data['_id']),
            $this->data, // new lead document to insert
            array("upsert" => true, "safe" => true)
            );

            print $this->data['_id'];
        } catch (Exception $e) {
            print "we are not able to update";
        }
    }

i have tried to do the followinf

if($this->data['_id'] == NULL || $this->data['_id'] == "")
            {
                $this->data['_id'] = new MongoId();
            }
            else
            {
             $this->data['_id'] = ObjectID($this->data['_id']);
            }   

but that seems not to help.

What Is happening is it inserts the first time correctly with ObjectID(idnumber) then when it goes to update is removes the ObjectID() and inserts a new lead with the same idnumber as before

so it looks like "IDNUMBER"


Solution

  • Your original code is close, but if you want to make a string _id the correct ObjectID type, use:

    $this->data['_id'] = new MongoId($this->data['_id']);