Skip to content

Instantly share code, notes, and snippets.

@DevBrent
Last active April 13, 2018 15:53
Show Gist options
  • Save DevBrent/cbe254d086793f7c5f76bbb673ef7bda to your computer and use it in GitHub Desktop.
Save DevBrent/cbe254d086793f7c5f76bbb673ef7bda to your computer and use it in GitHub Desktop.
MongoDB Index Export/Migration Tool

MongoDB Index Export/Migration Tool

Description:

Have you ever needed to copy your indexes from one platform to another without restoring a backup?

Instructions:

Run this script on the source database. You have one option which is to force the background option.

var always_background = true;


db.getCollectionNames()
.sort()
.forEach(function(collection) {
    indexes = db[collection].getIndexes();
    
    if (indexes && indexes.length > 0) {
        print("//Indexes for " + collection + ":");
    }
    
    indexes.forEach(function (index) {
       var key = JSON.stringify(index.key);
       delete index.v;
       delete index.ns;
       delete index.name;
       delete index.key;
       if (always_background) {
           index.background = true;
       }
       var options = JSON.stringify(index);
       
       if (key !== '{"_id":1}') {
           print('db.' + collection + '.createIndex(' + key + ', ' + options + ');');
       }
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment