Mongodb使用不同的值更新多个文档

时间:2013-05-20 13:26:10

标签: php mongodb mongodb-php mongodb-update

我正在尝试使用不同的值更新mongodb中的多个文档。

在mysql中我做了类似的事情:

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

现在,有可能在mongodb中进行吗?

2 个答案:

答案 0 :(得分:4)

此问题已在此处提出:MongoDB: insert on duplicate key update

在mongodb中,您可以使用Update命令中的 upsert 选项。它与ON DUPLICATE KEY UPDATE类似。 upsert 选项的定义:

  

一种更新,可以更新匹配的第一个文档   提供查询选择器,或者,如果没有文档匹配,则插入新的   具有查询选择器隐含的字段的文档   更新操作。

我已经查阅了PHP Mongo文档。在MongoCollection:Update命令的示例#2中,您有回复。

示例:

<?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));
}

?>

答案 1 :(得分:1)

如果您的SQL中的重复键是引用ID字段,那么它将如下所示:

// Your big array thing from your example
$objs = array(array('id'=>1,'lat'=>37.123,'lng'=>53.123),...,array('id'=>n,'lat'=>x,'lng'=>y));
// Start a new MongoClient
$m = new MongoClient();
// Select the DB and Collection
$collection = $m->selectCollection('DBNAME', 'COLLECTIONNAME');
// Loop through $objs
foreach($objs as $obj) {
    $collection->update(
        // If we find a matching ID, update, else insert
        array('id' => $obj['id']), 
        // The data we're inserting
        $obj, 
        // specify the upsert flag, to create a new one if it can't find
        array('upsert' => true) 
    );
}

基本上,更新命令(upsert设置为true)将更新与更新的第一个参数匹配的现有文档,或者插入新文档。 Mentor Reka的帖子更多地讨论了upserts如何工作,但上面的代码应该完全符合你的要求。