MongoDB如何将索引定义从一个集合复制到另一个集合?

ful*_*inu 5 mongodb

我知道有办法做db.collection.getIndexes()这将列出为集合定义的所有索引.有没有办法将这些索引定义复制并创建到另一个集合?

有很多,我不想一个接一个地做.

关于重复的问题评论:我不想复制一个集合.我希望以我可以应用于另一个集合的格式导出索引.

Man*_*vin 13

要直接在 MongoDB 中执行此操作,请执行以下操作:

以下命令将为所有集合的现有索引生成 mongo DB 查询,

db.getCollectionNames().forEach(function(col) {
    var indexes = db[col].getIndexes();
    indexes.forEach(function (c) {
        var fields = '', result = '', options = {};
        for (var i in c) {
            if (i == 'key') {
                fields = c[i];
            } else if (i == 'name' && c[i] == '_id_') {
                return;
            } else if (i != 'name' && i != 'v' && i != 'ns') {
                options[i] = c[i];
            }
        }
        var fields = JSON.stringify(fields);
        var options = JSON.stringify(options);
        if (options == '{}') {
            result = "db." + col + ".createIndex(" + fields + "); ";
        } else {
            result = "db." + col + ".createIndex(" + fields + ", " + options + "); ";
        }
        result = result
            .replace(/{"floatApprox":-1,"top":-1,"bottom":-1}/ig, '-1')
            .replace(/{"floatApprox":(-?\d+)}/ig, '$1')
            .replace(/\{"\$numberLong":"(-?\d+)"\}/ig, '$1');
        print(result);
    });
});
Run Code Online (Sandbox Code Playgroud)

上面的命令将根据您拥有的集合数量输出类似以下内容的内容

db.User.createIndex({"createdAt":-1}, {"background":true}); 

db.User.createIndex({"updatedAt":-1}, {"background":true}); 

db.Login.createIndex({"loginDate":-1}, {"background":true}); 
Run Code Online (Sandbox Code Playgroud)

因此,执行此操作后,复制上面生成的 MongoDB 查询以创建新集合的索引,更改其中的集合名称,然后执行它。

例如:要将属于 User 集合的所有索引复制到 UserNew 集合,我将查询的旧集合名称重命名为 new ,如下所示并执行它,就是这样,现在您已将所有索引复制到新集合中旧的。

db.UserNew.createIndex({"createdAt":-1}, {"background":true}); 

db.UserNew.createIndex({"updatedAt":-1}, {"background":true}); 
Run Code Online (Sandbox Code Playgroud)

学分: http: //aleksandrmaiorov.com/2019/04/29/mongo-how-to-copy-indexes-from-one-database-to-another/


小智 10

例如,我有一个现有的用户集合,其索引为_id_,name_1,email_1website_1

然后我有另一个名为usertest的集合,我想将索引从用户集合复制到usertest集合.以下命令适用于此方案:

  1. 复制索引键和索引选项

    var indexes = db.user.getIndexes();
    
    indexes.forEach(function(index){
        delete index.v;
        delete index.ns;
        var key = index.key;
        delete index.key
        var options = [];
        for (var option in index) {
            options.push(index[option]);
        }
       db.usertest.createIndex(key, options);
    });
    
    Run Code Online (Sandbox Code Playgroud)
  2. 仅复制索引键(批处理)

    var indexKeys = db.user.getIndexKeys();
    db.usertest.createIndexes(indexKeys);
    
    Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助.这是doc:createIndexes

  • `options.push(index['option']);` 中的 `'option'` 应该不带引号,对吗?我们想要变量,而不是字符串“选项”?而且,这可能会抛出“以数组形式提供的索引选项可能只指定三个值:name、unique、dropDups”,因此最好将“options”作为对象发送,因此第 7 行: var options = {}`,然后第 10 行:`options[option] = index[option]` (3认同)