有什么简单的方法吗?


当前回答

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

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

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

其他回答

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

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

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

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

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

这里有很多正确答案。我会选择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);
});"

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

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

执行常规查找并将前20条记录复制到test2。

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

或者通过某些标准进行筛选

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

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