2013-10-12 202 views
5

如何使用MongoDB克隆集合並忽略重複鍵?db.cloneCollection忽略重複密鑰

$ mongo items 
MongoDB shell version: 2.4.6 
connecting to: items 
> db.cloneCollection('localhost:27018', 'things') 
{ 
    "errmsg" : "exception: E11000 duplicate key error index: items.things.$_id_ dup key: { : ObjectId('52558bebdedc25038ed26d58') }", 
    "code" : 11000, 
    "ok" : 0 
} 

更好的是,有沒有一種更安全的方式來合併遠程集合與本地?如果db.cloneCollection被中斷,似乎沒有辦法在不清除所有重複項目並從頭開始重新啓動它的情況下「恢復」它。

回答

0

您可以創建另一個名爲say「things2」的集合並在那裏克隆遠程集合。然後使用無序批量插入到「things2」集合的每個文檔的「things」集合 - 它將忽略重複的鍵錯誤,直到整個批量插入完成。

db.cloneCollection('localhost:27018', 'things2'); 
 

 
var cursor = db.things2.find(); null; 
 

 
var bulk = db.things.initializeUnorderedBulkOp(); 
 

 

 
cursor.forEach(function(doc) { 
 
    bulk.insert(doc); 
 
}); 
 

 
bulk.execute();

,或者您可以使用所有來自「things2」收集的文件創建一個數組,然後選擇「插入」它與選項中的「事」集合{下令:假}

db.cloneCollection('localhost:27018', 'things_2'); 
 

 
var things2array = db.things2.find().toArray(); null; 
 

 
db.things.insert(things2array,{ ordered : false });