有什么简单的方法吗?


当前回答

在我的例子中,我必须在新集合中使用旧集合中的属性子集。因此,我最终在对新集合调用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"

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

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

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

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


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

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

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

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

如果RAM不是问题,使用insertMany比forEach循环快得多。

var db1 = connect('<ip_1>:<port_1>/<db_name_1>')
var db2 = connect('<ip_2>:<port_2>/<db_name_2>')

var _list = db1.getCollection('collection_to_copy_from').find({})
db2.collection_to_copy_to.insertMany(_list.toArray())