有什么简单的方法吗?


当前回答

这可能只是一个特殊情况,但对于一个包含100k文档的集合,其中包含两个随机字符串字段(长度为15-20个字符),使用哑mapreduce几乎是find-insert/copyTo速度的两倍:

db.coll.mapReduce(function() { emit(this._id, this); }, function(k,vs) { return vs[0]; }, { out : "coll2" })

其他回答

最好的方法是先做一个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禁用它。

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

如果在两个远程mongod实例之间,则使用

{ cloneCollection: "<collection>", from: "<hostname>", query: { <query> }, copyIndexes: <true|false> } 

参见http://docs.mongodb.org/manual/reference/command/cloneCollection/

我通常会这样做:

use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });

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