Skip to content

Instantly share code, notes, and snippets.

@meonkeys
Last active January 18, 2017 23:33
Show Gist options
  • Save meonkeys/eb42f53c462fa13a89c142a448b84b39 to your computer and use it in GitHub Desktop.
Save meonkeys/eb42f53c462fa13a89c142a448b84b39 to your computer and use it in GitHub Desktop.
Generate MongoDB index creation commands from the console
// Reads indexes from a running db and prints out commands to create those
// indexes in another db, for use in those cases where you restored a dump with
// --noIndexRestore.
// Just copy & paste into the MongoDB shell.
db.getCollectionNames().forEach(function(collection) {
var cleanIndexesBesidesId = [];
var indexes = db.getCollection(collection).getIndexes();
indexes.forEach(function(i) {
if (i.name === '_id_') {
return;
}
if (i.sparse) {
i.sparse = true; // might be int 1, let's conform
}
// let MongoDB set these
delete(i.v);
delete(i.ns);
// prune invalid keys because they crash MongoDB 3.4
delete(i.safe); // https://github.com/meteor/meteor/pull/4340
delete(i.w); // ??
cleanIndexesBesidesId.push(i);
});
if (cleanIndexesBesidesId.length) {
cleanIndexesBesidesId.forEach(function(i) {
var extraArgs = {};
extraArgs.name = i.name;
extraArgs.background = true;
if (i.unique) {
extraArgs.unique = true;
}
if (i.sparse) {
extraArgs.sparse = true;
}
if (i.expireAfterSeconds) {
extraArgs.expireAfterSeconds = i.expireAfterSeconds;
}
print("db['" + collection + "'].createIndex(" + JSON.stringify(i.key) + ',' + JSON.stringify(extraArgs) + ');');
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment