[英]Mongodb update several documents with different values
i am trying to update several documents in mongodb with different values each. 我试图用不同的值更新mongodb中的几个文档。
In mysql I do something like this: 在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)";
Now, is it possible to do it in mongodb? 现在,可以在mongodb中做到吗?
This question has already been asked here: MongoDB: insert on duplicate key update 在这里已经问过这个问题: MongoDB:在重复的密钥更新上插入
In mongodb you can use the upsert option on Update
command. 在mongodb中,您可以在Update
命令上使用upsert选项。 It's similar as ON DUPLICATE KEY UPDATE
. 它类似于ON DUPLICATE KEY UPDATE
。 Definition of upsert option: upsert选项的定义:
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. 我已经查阅了PHP Mongo文档。 In example #2 of MongoCollection:Update
command you have your response. 在MongoCollection:Update
命令的示例#2中 ,您将得到响应。
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));
}
?>
If you're duplicate key in your SQL is referencing the ID
field, then it would be as follows: 如果您的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)
);
}
Basically, the update command (with upsert
set to true) will either update an existing document that matches the first parameter of the update, or insert a new document. 基本上,更新命令(将upsert
设置为true)将更新与更新的第一个参数匹配的现有文档,或插入一个新文档。 Mentor Reka 's post talks more about how upserts work, but the code above should do exactly what you're looking for. Mentor Reka的帖子更多地讨论了upsert的工作原理,但是上面的代码应该可以完全满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.