有什么简单的方法吗?


当前回答

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

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

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

其他回答

以防一些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"

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

对于大容量的集合,可以使用Bulk.insert()

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

这将节省很多时间。 在我的例子中,我用1219个文档复制集合:iter vs Bulk(67秒vs 3秒)

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

正如在其他答案中给出的,最快的解决方案应该是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)
})

我知道这个问题已经被回答了,但我个人不会做@JasonMcCays的回答,因为光标流的事实,这可能会导致无限的游标循环,如果集合仍在使用。相反,我将使用snapshot():

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

@bens的回答也很好,不仅适用于集合的热备份,而且mongorestore不需要共享同一个mongod。