有什么简单的方法吗?
当前回答
目前,MongoDB中还没有这样的命令。请注意带有相关功能请求的JIRA票据。
你可以这样做:
db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_database>')['<collection_name>'].insert(d); });
请注意,在这种情况下,两个数据库需要共享同一个mongod才能正常工作。
除此之外,您还可以从一个数据库对一个集合进行mongodump,然后再将该集合恢复到另一个数据库。
其他回答
以防一些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);
});"
对于大容量的集合,可以使用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秒)
您可以使用聚合框架解决您的问题
db.oldCollection.aggregate([{$out : "newCollection"}])
需要注意的是,oldCollection中的索引不会复制到newCollection中。
最好的方法是先做一个mongodump,然后再做mongorestore。您可以通过以下方式选择集合:
mongodump -d some_database -c some_collection
[可选地,压缩转储(zip some_database.zip some_database/* -r)并将其scp到其他地方]
然后恢复:
mongorestore -d some_other_db -c some_or_other_collection dump/some_collection.bson
some_or_other_collection中的现有数据将被保留。这样,您就可以将一个集合从一个数据库“附加”到另一个数据库。
在版本2.4.3之前,您还需要在复制数据后添加回索引。从2.4.3开始,这个过程是自动的,您可以使用——noIndexRestore禁用它。
推荐文章
- 如何排序mongodb与pymongo
- 如何在mongodb上导入。bson文件格式
- JSON文件的蒙古导入
- 如何删除mongodb中的数组元素?
- 修改MongoDB数据存储目录
- 在MongoDB中查找重复的记录
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 在猫鼬,我如何排序的日期?(node . js)
- 将映像存储在MongoDB数据库中
- 重复Mongo ObjectId的可能性在两个不同的集合中生成?
- Redis比mongoDB快多少?
- 无法连接到服务器127.0.0.1:27017
- 如何创建数据库的MongoDB转储?
- 如何将MongoDB作为Windows服务运行?
- 如何监听MongoDB集合的变化?