首頁 > 軟體

mongodb表索引備份,索引的匯出匯入

2021-01-16 13:30:08

背景

  • 發現有兩個mongodb環境的資料庫表索引不一致,另一個資料庫有索引缺失,需要將一個資料庫裡的所有表索引匯入到另一個資料庫
  • 也可用於單獨備份資料庫所有表的索引

寫mongo shell的js指令碼可參考官方檔案https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell

匯出匯入索引的js指令碼

// 當前指令碼名為exportImportIndexes.js
let joinStr = "*_*";

// 查詢所有表的索引
function findAllIndexes() {
    // 獲取所有表
    let allCollections = db.getCollectionNames();
    for (var colName of allCollections) {
        let indexes = db.getCollection(colName).getIndexes();
        // 輸出表索引資訊
        print(colName, joinStr, JSON.stringify(indexes));
    }
}

// 新增所有表的索引
// 前提是通過findAllIndexes函數將所有表的索引寫入了當前執行路徑下的all_indexes.txt檔案
function addAllIndexes() {
    // 獲取所有索引,一行代表一張表的索引
    let indexes = cat('./all_indexes.txt');
    lines = indexes.split('n');
    // 遍歷所有表的索引
    for (var line of lines) {
        print("line:", line);
        let items = line.split(joinStr);
        if (items.length !== 2) {
            continue
        }

        let colName = items[0].trim();
        let indexes = items[1].trim();

        if (indexes === "") {
            continue
        }

        for (var index of JSON.parse(indexes)) {
            print("begin add collectionName:", colName, "index:", JSON.stringify(index));
            // 一次只建立一個索引,防止批次建立索引過程中的錯誤可能導致多個索引建立失敗
            let rs = db.runCommand(
                {
                    createIndexes: colName,
                    indexes: [index]
                }
            );
            print("operation result:", JSON.stringify(rs),"n");
        }
        print("n");
    }
}

// 匯出索引執行findAllIndexes
// findAllIndexes();

// 匯入索引執行addAllIndexes
// addAllIndexes();

匯出匯入索引的執行過程

假設要匯出的mongodb地址是localhost:27011,db是test1
要匯入的mongodb地址是localhost:27012,db是test2

  • 匯出時只將"findAllIndexes();"這一行取消註釋,執行命令: mongo localhost:27011/test1 exportImportIndexes.js > all_indexes.txt
  • 匯入時只將"addAllIndexes();"這一行取消註釋,執行命令: mongo localhost:27012/test2 exportImportIndexes.js > index_result.txt

IT145.com E-mail:sddin#qq.com