Answer a question

I know there's a way to do db.collection.getIndexes() Which will list all the indexes defined for a collection. Is there a way to copy and create those index definitions to another collection?

There's a lot of them and I don't want to do them one by one.

regarding the duplicated question comment: I do not wish to copy a collection. I wish to export indexes in a format that I can apply to another collection.

Answers

For example I have one existing user collection with indexes _id_, name_1, email_1 and website_1

Then I have another collection called usertest, I want to copy indexes from user collection to usertest collection. The following commands works for this scenario:

  1. Copy both index key and index options

    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);
    });
    
  2. Copy index key only (batch processing)

    var indexKeys = db.user.getIndexKeys();
    db.usertest.createIndexes(indexKeys);
    

Hope this will be helpful. Here's the doc: createIndexes

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐