2017-10-28 188 views
0

我有一个MongoDB开发集群,我随着时间的推移创建索引作为开发改进的一部分。在测试/生产MongoDB集群上,我也想维护相同的索引。MongoDB将所有现有索引迁移到新数据库

那么我如何获取现有集合的所有索引并在新数据库上创建相同的集合索引?

回答

1

从蒙戈外壳,切换到数据库中,你要收集指标

第1步:切换到现有的数据库和下面的脚本运行

> use my_existing_db

下面的脚本遍历所有的收集并构建每个收藏的run command

var database = ‘my_new_db' // SHOULD ALWAYS MATCH DESTINATION DB NAME 
db.getCollectionNames().forEach(function(collection){  
    var command = {} 
    var indexes = []  
    idxs = db.getCollection(collection).getIndexes()   
    if(idxs.length>1){ 
     idxs.forEach(function(idoc){ 
      if(idoc.name!='_id_'){ 
       var ns = database+"."+idoc.ns.substr(idoc.ns.indexOf('.') + 1) 
       idoc.ns = ns 
       indexes.push(idoc) 
      } 
     })   
     command['createIndexes'] = collection 
     command['indexes'] = indexes   
     print('db.runCommand(') 
     printjson(command)  
     print(')') 
    } 
}) 

脚本输出runCommand对每个集合

第2步:切换到新的数据库,并执行runCommands。完成,干杯!

> use my_new_db

runCommands会是这样的。你可以一次运行所有的命令。

db.runCommand(
{ 
    "createIndexes" : "foo", 
    "indexes" : [ 
     { 
      "v" : 2, 
      "key" : { 
       "xy_point" : "2d" 
      }, 
      "name" : "xy_point_2d", 
      "ns" : "my_new_db.foo", 
      "min" : -99999, 
      "max" : 99999 
     }, 
     { 
      "v" : 2, 
      "key" : { 
       "last_seen" : 1 
      }, 
      "name" : "last_seen_1", 
      "ns" : "my_new_db.foo", 
      "expireAfterSeconds" : 86400 
     }, 
     { 
      "v" : 2, 
      "key" : { 
       "point" : "2dsphere" 
      }, 
      "name" : "point_2dsphere", 
      "ns" : "my_new_db.foo", 
      "background" : false, 
      "2dsphereIndexVersion" : 3 
     } 
    ] 
} 
) 
db.runCommand(
{ 
    "createIndexes" : "bar", 
    "indexes" : [ 
     { 
      "v" : 2, 
      "unique" : true, 
      "key" : { 
       "date" : 1, 
       "name" : 1, 
       "age" : 1, 
       "gender" : 1 
      }, 
      "name" : "date_1_name_1_age_1_gender_1", 
      "ns" : "my_new_db.bar" 
     } 
    ] 
} 
)