有什么简单的方法吗?


当前回答

这可以使用Mongo的db来完成。copyDatabase方法:

db.copyDatabase(fromdb, todb, fromhost, username, password)

参考:http://docs.mongodb.org/manual/reference/method/db.copyDatabase/

其他回答

在我的例子中,我必须在新集合中使用旧集合中的属性子集。因此,我最终在对新集合调用insert时选择了这些属性。

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

使用pymongo,你需要在同一个mongod上有两个数据库,我做了以下工作:


Db =原始数据库 Db2 =要复制到的数据库

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

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

这里有很多正确答案。我会选择mongodump和mongorestore作为一个大的收藏:

mongodump --db fromDB --gzip --archive | mongorestore --drop --gzip --archive --nsFrom "fromDB.collectionName" --nsTo "toDB.collectionName"

虽然如果我想快速复制,它很慢,但它是有效的:

use fromDB 
db.collectionName.find().forEach(function(x){
   db.getSiblingDB('toDB')['collectionName'].insert(x);
});"

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

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