Translate

Friday, April 22, 2016

Dump Mongo Indexes to Re-playable Script

When using mongo, we at times create indexes in our production environment to support slow queries and need to bring those indexes back into other environments for testing and consistency. I have not found anything similar, but this script dumps the mongo indexes to output for every collection in every database that way this output can be run against mongo to create them. Enjoy!
db = db.getSiblingDB('admin');
var dbs = db.runCommand({ 'listDatabases': 1 }).databases;

var result = '';

dbs.forEach(function(database) {
  if(database.name !== 'admin' && database.name !== 'local' && database.name !== 'system') {
  
    result += 'db = db.getSiblingDB(\"' + database.name + '\");\n\n';
   
    db = db.getSiblingDB(database.name);
  
    db.getCollectionNames().forEach(function(collection) {
  
      if(collection !== 'system.users') {
  
        indexes = db[collection].getIndexes();
   
        indexes.forEach(function(index) {
     
          if(index.key._id === undefined) {

            result += 'db.' + collection + '.ensureIndex(' + tojson(index.key) + ',  { \"name\" : \"' + index.name + '\"';
       
            if(index.background !== undefined) {
         
              result += ', \"background\" : ' + index.background;
            }
     
            result += ' });\n';
          }  
        });
      }
    });
    
    result += '\n';
  }
});
     
print(result);

No comments:

Post a Comment

Codementor

Ryan Kuhn

★★★★★

Expertise