Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidebettio/59cab41d1719c36a13c5a85394d17a8d to your computer and use it in GitHub Desktop.
Save davidebettio/59cab41d1719c36a13c5a85394d17a8d to your computer and use it in GitHub Desktop.
Backup mongodb indexes
print(`// Backup indexes of : ${db.getName()} : database`);
print(`use ${db.getName()};`);
db.getCollectionNames().forEach(function (collection) {
indexes = db.getCollection(collection).getIndexes().forEach(function (index) {
if (index.name === '_id_') return; // skip defalut _id indexes
const keys = tojsononeline(index.key);
delete index.id; delete index.key; delete index.v; delete index.ns;
print(`db.${collection}.createIndex(${keys}, ${tojsononeline(index)});`);
});
});
mongo --quiet mongodb://localhost:27017/mydatabase indexes-backup.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment