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


Mongodb update several documents with different values

我正在尝试更新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?

这个问题已经在这里问过了: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));
}
?>

如果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) 
    );
}

基本上,update命令(将upsert设置为true)将更新与更新的第一个参数匹配的现有文档,或者插入一个新文档。导师Reka的文章更多地讨论了upserts是如何工作的,但上面的代码应该做的正是你所寻找的。