5

如何使用 MongoDB 克隆集合并忽略重复键?

$ 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被中断,似乎没有办法在不清除所有重复项并从头开始重新启动它的情况下“恢复”它。

4

1 回答 1

0

您可以创建另一个名为“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”集合中的所有文档创建一个数组,然后使用选项 {ordered: false } 将其“插入”到“things”集合中

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

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

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

于 2015-11-24T11:27:52.173 回答