有什么简单的方法吗?


当前回答

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

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

克隆:

> 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'
      }
  );

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

其他回答

这可能只是一个特殊情况,但对于一个包含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 --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);
});"

我会滥用mongo cli mongo doc中的连接功能。这意味着您可以启动一个或多个连接。 如果您想将客户集合从test复制到同一服务器中的test2。首先你开始mongo shell

use test
var db2 = connect('localhost:27017/test2')

执行常规查找并将前20条记录复制到test2。

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

或者通过某些标准进行筛选

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

只需将localhost更改为IP或主机名即可连接到远程服务器。我使用它将测试数据复制到测试数据库进行测试。

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

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

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

在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