【问题标题】:MongoDB Migrate all existing indexes to new databaseMongoDB 将所有现有索引迁移到新数据库
【发布时间】:2018-04-10 02:53:35
【问题描述】:

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

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

【问题讨论】:

    标签: mongodb indexing multi-index robo3t


    【解决方案1】:

    从 mongo shell,切换到要收集索引的数据库

    第 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"
            }
        ]
    }
    )
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2021-03-17
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2013-09-25
      • 2015-10-29
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多