Skip to content

Instantly share code, notes, and snippets.

@danyanya
Last active December 25, 2019 11:58
Show Gist options
  • Save danyanya/9441b36db652aacc6d0f68a92699a915 to your computer and use it in GitHub Desktop.
Save danyanya/9441b36db652aacc6d0f68a92699a915 to your computer and use it in GitHub Desktop.
mongodb export indexes with expiration
var always_background = true;
db.getCollectionNames().forEach(function(collection) {
indexes = db.getCollection(collection).getIndexes();
if(indexes && indexes.length>0) {
print("//Indexes for " + collection + ":");
indexes.forEach(function(index) {
var options = {};
if(index.unique) {
options.unique = index.unique;
}
if(index.sparse) {
options.sparse = index.sparse;
}
if(index.background) {
options.background = index.background;
}
if(index.expireAfterSeconds) {
options.expireAfterSeconds = index.expireAfterSeconds;
}
if(always_background) {
options.background = true;
}
options = JSON.stringify(options);
var key = JSON.stringify(index.key);
if(key !== '{"_id":1}') {
print('db.getCollection("' + collection + '").createIndex(' + key + ', ' + options + ');');
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment