Skip to content

Instantly share code, notes, and snippets.

@ixti
Last active May 4, 2021 08:37
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ixti/5359329 to your computer and use it in GitHub Desktop.
Save ixti/5359329 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) + ")");
}
});
});
@ixti
Copy link
Author

ixti commented Apr 10, 2013

USAGE:

wget -qO- http://goo.gl/h91Hq | mongo --quiet <db-name>

@tonyt73
Copy link

tonyt73 commented Jul 12, 2017

Here is a version to read all the databases and extract all the index (except admin and local)

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) + ")");
	    }
	  });
	});
  	}
});

@nicothed
Copy link

Great script, thanks!

Here is a version to recreate them all with options, and with the new createIndex command instead of ensureIndex (since mongoDB 3.0)

db.getCollectionInfos().forEach(function(coll) {
//print( JSON.stringify( coll ))
if (coll.type === "collection" ) {
db[coll.name].getIndexes().forEach(function(index) {
if ("id" !== index.name) {
//print( JSON.stringify( index ))
var indexKey = index.key // save the key, and transform index into the "options"
delete index.v
delete index.key
index.background = true // optional: force background to be true
print("db." + coll.name + ".createIndex(" + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
}
});
}
});

@shrikanthdvg
Copy link

Thanks @tonyt73, helped a lot.

@cn73
Copy link

cn73 commented Nov 8, 2019

@nicothed thxs!

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