有什么简单的方法吗?


当前回答

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

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

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

其他回答

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

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


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

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

从现有的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

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

你可以随时使用Robomongo。从v0.8.3开始,有一个工具可以通过右键单击集合并选择“将集合复制到数据库”来完成此操作。

具体操作请参见http://blog.robomongo.org/whats-new-in-robomongo-0-8-3/

由于这个特性在0.8.5版本中被移除,所以如果你想尝试的话,你将不得不使用0.8.3或0.8.4。