11

mongodb表索引备份,索引的导出导入

 3 years ago
source link: http://www.cnblogs.com/fireyun/p/14285566.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

背景

  • 发现有两个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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK