解决方案一
通过copydb拷贝原来的数据,然后drop原来的DB(4.0及以前版本可用,新版本不可用)
db.copyDatabase(‘old_name‘, ‘new_name‘);
use old_name
db.dropDatabase();
解决方案二
- 通过mongodump 导出源库数据
- 通过mongorestore 恢复数据到新库
- 删除源库
解决方案三
通过renameCollection将旧集合重命名到新集合
> use db5
switched to db db5
> show collections
db5
> db.adminCommand({renameCollection:"db5.db5",to:"db6.db5"})
{ "ok" : 1 }
>
> use db6
switched to db db6
> show collections
db5
db6
maclean
maclean1
> use db5
switched to db db5
> show collections
集合较多的话,也可以进行批量renameCollection
> var source = "db6";
> var dest = "db5";
> var colls = db.getSiblingDB(source).getCollectionNames();
> for (var i = 0; i < colls.length; i++) {
... var from = source + "." + colls[i];
... var to = dest + "." + colls[i];
... db.adminCommand({renameCollection: from, to: to});
... }
{ "ok" : 1 }
>
>
> use db5
switched to db db5
> show collections
db5
db6
maclean
maclean1
注意
方案三只适用于单机版或者副本集架构,分片集群暂时不支持。