2013-10-12 216 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 });