Search code examples
phpmongodbphp-mongodbmongodb-update

Mongodb update several documents with different values


i am trying to update several documents in mongodb with different values each.

In mysql I do something like this:

$objs = array(array('id'=>1,'lat'=>37.123,'lng'=>53.123),...,array('id'=>n,'lat'=>x,'lng'=>y));

$sql = "INSERT INTO objects (objectId,latitude,longitude) VALUES";
        foreach ($objs as $obj) {
            $id = $obj['id'];
            $lat = $obj['lat'];
            $lng = $obj['lng'];
            $sql .= "($id,$lat,$lng),";
        }
        $sql = substr_replace($sql ," ",-1);    
        $sql.= "ON DUPLICATE KEY UPDATE latitude=VALUES(latitude),longitude=VALUES(longitude)";

Now, is it possible to do it in mongodb?


Solution

  • This question has already been asked here: MongoDB: insert on duplicate key update

    In mongodb you can use the upsert option on Update command. It's similar as ON DUPLICATE KEY UPDATE. Definition of upsert option:

    A kind of update that either updates the first document matched in the provided query selector or, if no document matches, inserts a new document having the fields implied by the query selector and the update operation.

    I have consulting the PHP Mongo Documentation. In example #2 of MongoCollection:Update command you have your response.

    Example:

    <?php
    $objs = array(array('id'=>1,'lat'=>37.123,'lng'=>53.123), array('id'=>n,'lat'=>x,'lng'=>y));
    
    foreach($objs as $obj)
    {
        // Parameters: [1] Description of the objects to update. [2] The object with which to update the matching records. [3] Options 
        $collection->update(array("id" => $obj["id"]), $obj, array("upsert" => true));
    }
    
    ?>