Skip to content

Instantly share code, notes, and snippets.

@dublado
Forked from ixti/show-indexes.js
Created August 28, 2020 20:50
Show Gist options
  • Save dublado/16175aca283f183e9957c6b822803124 to your computer and use it in GitHub Desktop.
Save dublado/16175aca283f183e9957c6b822803124 to your computer and use it in GitHub Desktop.
Small script that extracts all non-default indexes from MongoDB
rs.slaveOk();
db.getCollectionNames().forEach(function(coll) {
db[coll].getIndexes().forEach(function(index) {
if ("_id_" !== index.name) {
print("db." + coll + ".ensureIndex(" + tojson(index.key) + ")");
}
});
});
//all databases
db.getMongo().getDBNames().forEach(function(dbName) {
if (dbName != "admin" && dbName != "local") {
db.getSiblingDB(dbName).getCollectionNames().forEach(function(coll) {
db.getSiblingDB(dbName)[coll].getIndexes().forEach(function(index) {
if ("_id_" !== index.name) {
print("db.getSiblingDB('" + dbName + "')." + coll + ".ensureIndex(" + tojson(index.key) + ")");
}
});
});
}
});
@dublado
Copy link
Author

dublado commented Aug 28, 2020

db.getMongo().getDBNames().forEach(function(dbName) {
if (dbName != "admin" && dbName != "local") {
db.getSiblingDB(dbName).getCollectionNames().forEach(function(coll) {
db.getSiblingDB(dbName)[coll].getIndexes().forEach(function(index) {
if ("id" !== index.name) {
print("db.getSiblingDB('" + dbName + "')." + coll + ".ensureIndex(" + tojson(index.key) + ")");
}
});
});
}
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment