如何在 MongoDB 中将集合从一个数据库复制到另一个数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11554762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:44:45  来源:igfitidea点击:

How to copy a collection from one database to another in MongoDB

mongodb

提问by EasonBlack

Is there a simple way to do this?

有没有一种简单的方法可以做到这一点?

采纳答案by Jason McCay

At the moment there is no command in MongoDB that would do this. Please note the JIRA ticket with related feature request.

目前 MongoDB 中没有可以执行此操作的命令。请注意带有相关功能请求JIRA 票证

You could do something like:

你可以这样做:

db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_database>')['<collection_name>'].insert(d); });

Please note that with this, the two databases would need to share the same mongod for this to work.

请注意,这两个数据库需要共享同一个 mongod 才能工作。

Besides this, you can do a mongodump of a collection from one database and then mongorestore the collection to the other database.

除此之外,您可以对一个数据库中的集合进行 mongodump,然后将集合 mongorestore 到另一个数据库。

回答by Ben

The best way is to do a mongodump then mongorestore.

最好的方法是先做一个 mongodump,然后再做 mongorestore。

You can select the collection via:

您可以通过以下方式选择集合:

mongodump -d some_database -c some_collection

[Optionally, zip the dump (zip some_database.zip some_database/* -r) and scpit elsewhere]

[可选地,将转储 ( zip some_database.zip some_database/* -r)压缩到scp其他地方]

Then restore it:

然后恢复它:

mongorestore -d some_other_db -c some_or_other_collection dump/some_collection.bson

Existing data in some_or_other_collectionwill be preserved. That way you can "append" a collection from one database to another.

中的现有数据some_or_other_collection将被保留。这样您就可以将一个数据库中的集合“附加”到另一个数据库中。

Prior to version 2.4.3, you will also need to add back your indexes after you copy over your data. Starting with 2.4.3, this process is automatic, and you can disable it with --noIndexRestore.

在版本 2.4.3 之前,您还需要在复制数据后重新添加索引。从 2.4.3 开始,此过程是自动的,您可以使用 禁用它--noIndexRestore

回答by Anuj Gupta

Actually, there isa command to movea collection from one database to another. It's just not called "move" or "copy".

其实,有一个命令移动从一个数据库收集到另一个。它只是不称为“移动”或“复制”。

To copy a collection, you can clone it on the same db, then move the clone.

要复制集合,您可以在同一个数据库上克隆它,然后移动克隆。

To clone:

克隆:

> use db1
> db.source_collection.find().forEach( function(x){db.collection_copy.insert(x)} );

To move:

移动:

> use admin
switched to db admin
> db.runCommand({renameCollection: 'db1.source_collection', to: 'db2.target_collection'}) // who'd think rename could move?

The other answers are better for copying the collection, but this is especially useful if you're looking to move it.

其他答案更适合复制集合,但如果您想移动它,这尤其有用。

回答by wayne

I would abuse the connect function in mongo cli mongo doc. so that means you can start one or more connection. if you want to copy customer collection from test to test2 in same server. first you start mongo shell

我会滥用 mongo cli mongo doc 中的连接功能。这意味着您可以启动一个或多个连接。如果要将客户集合从 test 复制到同一服务器中的 test2。首先你启动 mongo shell

use test
var db2 = connect('localhost:27017/test2')

do a normal find and copy the first 20 record to test2.

做一个正常的查找并将前 20 条记录复制到 test2。

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

or filter by some criteria

或按某些标准过滤

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

just change the localhost to IP or hostname to connect to remote server. I use this to copy test data to a test database for testing.

只需将 localhost 更改为 IP 或主机名即可连接到远程服务器。我用它来将测试数据复制到测试数据库进行测试。

回答by es cologne

If between two remote mongod instances, use

如果在两个远程 mongod 实例之间,请使用

{ cloneCollection: "<collection>", from: "<hostname>", query: { <query> }, copyIndexes: <true|false> } 

See http://docs.mongodb.org/manual/reference/command/cloneCollection/

请参阅http://docs.mongodb.org/manual/reference/command/cloneCollection/

回答by ffflabs

I'd usually do:

我通常会这样做:

use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });

回答by nametal

for huge size collections, you can use Bulk.insert()

对于大型集合,您可以使用Bulk.insert()

var bulk = db.getSiblingDB(dbName)[targetCollectionName].initializeUnorderedBulkOp();
db.getCollection(sourceCollectionName).find().forEach(function (d) {
    bulk.insert(d);
});
bulk.execute();

This will save a lot of time. In my case, I'm copying collection with 1219 documents: iter vs Bulk (67 secs vs 3 secs)

这将节省大量时间。就我而言,我正在复制包含 1219 个文档的集合:iter vs Bulk(67 秒 vs 3 秒)

回答by Alexander Makarov

You can use aggregation framework to resolve your issue

您可以使用聚合框架来解决您的问题

db.oldCollection.aggregate([{$out : "newCollection"}])

It shoul be noted, that indexes from oldCollection will not copied in newCollection.

应该注意的是,oldCollection 中的索引不会复制到 newCollection 中。

回答by vbhakta

Using pymongo, you need to have both databases on same mongod, I did the following:

使用 pymongo,您需要在同一个 mongod 上拥有两个数据库,我执行了以下操作:



db= original database
db2= database to be copied to

db= 原始数据库
db2= 要复制到的数据库

cursor = db["<collection to copy from>"].find()
for data in cursor:
    db2["<new collection>"].insert(data)

回答by Vajk Hermecz

This might be just a special case, but for a collection of 100k documents with two random string fields (length is 15-20 chars), using a dumb mapreduce is almost twice as fast as find-insert/copyTo:

这可能只是一个特例,但是对于具有两个随机字符串字段(长度为 15-20 个字符)的 100k 文档的集合,使用哑 mapreduce 的速度几乎是 find-insert/copyTo 的两倍:

db.coll.mapReduce(function() { emit(this._id, this); }, function(k,vs) { return vs[0]; }, { out : "coll2" })