有什么简单的方法吗?


当前回答

令人难以置信的是,对于缓慢得令人痛苦的一份一份的数据拷贝,有多少人投了赞成票。

正如在其他答案中给出的,最快的解决方案应该是mongodb / mongorestore。不需要将转储文件保存到本地磁盘,您可以将转储文件直接管道到mongorestore:

mongodump --db=some_database --collection=some_collection --archive=- | mongorestore --nsFrom="some_database.some_collection" --nsTo="some_or_other_database.some_or_other_collection" --archive=-

如果您运行一个分片集群,默认情况下新集合是不分片的。所有数据最初都写入主分片。这可能会导致磁盘空间出现问题,并为集群平衡增加额外负载。在你导入数据之前,最好像这样预先分割你的集合:

sh.shardCollection("same_or_other_database.same_or_other_collection", { <shard_key>: 1 });
db.getSiblingDB("config").getCollection("chunks").aggregate([
   { $match: { ns: "some_database.some_collection"} },
   { $sort: { min: 1 } },
   { $skip: 1 }
], { allowDiskUse: true }).forEach(function (chunk) {
   sh.splitAt("same_or_other_database.same_or_other_collection", chunk.min)
})

其他回答

我通常会这样做:

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

以防一些heroku用户在这里遇到麻烦,像我一样想从登台数据库复制一些数据到生产数据库,反之亦然,这里是如何非常方便地做到这一点(注意,我希望没有错字在那里,不能检查它atm。,我会尽快确认代码的有效性):

to_app="The name of the app you want to migrate data to"
from_app="The name of the app you want to migrate data from"
collection="the collection you want to copy"
mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"

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

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

使用“Studio3T for MongoDB” 通过单击数据库,集合或特定的集合具有导出和导入工具 下载链接:https://studio3t.com/download/

从现有的MongoDB atlas cluster DB导入数据最简单的方法是使用MongoDB & mongorestore命令。

要从现有的DB中创建转储,您可以使用:

mongodump --uri="<connection-uri>"

还有其他连接选项,可以在这里查找:https://www.mongodb.com/docs/database-tools/mongodump/

在dump/目录中成功创建转储后,您可以使用导入数据到您的其他db,如下所示:

mongorestore --uri="<connection-uri-of-other-db>" <dump-file-location>

类似地,对于mongorestore,还有其他连接选项,可以在命令中查找以恢复特定的集合: https://www.mongodb.com/docs/database-tools/mongorestore/

转储文件的位置将在转储目录中。可能存在与您转储的DB名称相同的子目录。例如,如果您转储了测试数据库,那么转储文件的位置将是/dump/test