db.cloneCollection忽略重复的键 [英] db.cloneCollection ignore duplicate keys

查看:100
本文介绍了db.cloneCollection忽略重复的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用MongoDB克隆集合并忽略重复的密钥?

How do I clone a collection with MongoDB and ignore duplicate keys?

$ 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被打断,似乎没有办法在不清除所有重复项并从头开始的情况下对其进行恢复".

Better yet, is there a safer way of merging a remote collection with a local one? If db.cloneCollection is interrupted, there doesn't seem to be a way to "resume" it without wiping out all of the duplicate items and restarting it from the beginning.

推荐答案

您可以创建另一个名为say"things2"的集合,然后在其中克隆远程集合.然后对"things2"集合的每个文档对"things"集合使用无序批量插入-在完成整个批量插入之前,它将忽略重复的键错误.

You can create another collection named say "things2" and clone there the remote collection. Then use unordered bulk insert to the "things" collection for each document of "things2" collection - it will ignore duplicate key errors until the whole bulk insert is done.

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"集合中

or you can create an array with all the documents from "things2" collection and then "insert" it to the "things" collection with the option { ordered: false }

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

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

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

这篇关于db.cloneCollection忽略重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆