有什么简单的方法吗?


当前回答

对于大容量的集合,可以使用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秒)

其他回答

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

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

实际上,有一个命令用于将集合从一个数据库移动到另一个数据库。它只是不叫“移动”或“复制”。

若要复制集合,可以在同一数据库上克隆它,然后移动克隆的集合。

克隆:

> use db1
switched to db db1

> db.source_collection.find().forEach(
      function(x){
          db.collection_copy.insert(x)
      }
  );

移动:

> use admin
switched to db admin

> db.runCommand(
      {
          renameCollection: 'db1.source_collection',
          to              : 'db2.target_collection'
      }
  );

其他答案更适合复制集合,但如果您希望移动集合,这个答案尤其有用。

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


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

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

在MongoDB中将一个集合(myCollection1)从一个数据库复制到另一个数据库,

**Server1:**
myHost1.com 
myDbUser1
myDbPasword1
myDb1
myCollection1

outputfile:
myfile.json 

**Server2:**
myHost2.com 
myDbUser2
myDbPasword2
myDb2
myCollection2 

你可以这样做:

mongoexport  --host myHost1.com --db myDb1 -u myDbUser1  -p myDbPasword1 --collection myCollection1   --out  myfile.json 

然后:

mongoimport  --host myHost2.com --db myDb2 -u myDbUser2  -p myDbPasword2 --collection myCollection2   --file myfile.json 

另一种情况,使用CSV文件:

Server1:
myHost1.com 
myDbUser1
myDbPasword1
myDb1
myCollection1
fields.txt
    fieldName1
    fieldName2

outputfile:
myfile.csv

Server2:
myHost2.com 
myDbUser2
myDbPasword2
myDb2
myCollection2

你可以这样做:

mongoexport  --host myHost1.com --db myDb1 -u myDbUser1  -p myDbPasword1 --collection myCollection1   --out  myfile.csv --type=csv

在CSV文件中添加列类型(name1.decimal(),name1.string()..),然后:

mongoimport  --host myHost2.com --db myDb2 -u myDbUser2  -p myDbPasword2 --collection myCollection2   --file myfile.csv --type csv --headerline --columnsHaveTypes

我通常会这样做:

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