2017-10-28 187 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" 
     } 
    ] 
} 
)