2013-05-20 16 views
1

我試圖用不同的值更新mongodb中的幾個文件。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中?

+0

是的即時通訊現在這樣做,但我認爲這是相當無效的,因爲你必須訪問數據庫相同的時間你需要編輯它。儘管sql方式的所有循環都是在DB中完成的。 – leojg

回答

3

這個問題已經在這裏問:MongoDB: insert on duplicate key update

MongoDB中您可以使用UPSERT選項上Update命令。它與ON DUPLICATE KEY UPDATE類似。的定義UPSERT選項:

的一種更新的,要麼更新在 提供的查詢選擇匹配的第一個文件,或者,如果沒有文件匹配,插入具有由查詢選擇隱含領域的新 文件和 更新操作。

我已經諮詢了PHP Mongo文檔。在例子#2MongoCollection:Update命令你有你的迴應。

例子:

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

?> 
+0

是的,基本上我現在正在這樣做,但它是最好的方式嗎?謝謝回答。 – leojg

+0

如果這是你想要的最好(快速和可靠)的方式公平,我不知道。但它是你需要的。我不知道其他方法,但有興趣知道它們是否存在。如果你找到一個,請在這裏張貼:) –

+0

這是不真實的做一個查詢? – xfg

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是如何工作的,但是上面的代碼應該完全符合你的要求。