Skip to content

Instantly share code, notes, and snippets.

@Climax777
Created May 26, 2014 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Climax777/40eae9e4abe7ec94d4e3 to your computer and use it in GitHub Desktop.
Save Climax777/40eae9e4abe7ec94d4e3 to your computer and use it in GitHub Desktop.
MongoDB shell helper for dropping a collection while keeping the indexes
collectionsafedropper = function(database,col) {
var thedb = db.getSiblingDB(database);
var thecoll = thedb[col];
var indexes = thecoll.getIndexes();
print("Dropping: ", database.toString() + "." + col.toString());
thecoll.drop();
indexes.forEach(function(index) {
var key = index.key;
var options = {};
if(index["sparse"] != null && index["sparse"] == true) {
// Seems that the shell uses an integer value for sparse
options.sparse=1;
}
if(index["unique"] != null && index["unique"] == true) {
// Seems that the shell uses a boolean value for unique
options.unique=true;
}
if(index["background"] != null && index["background"] == true) {
// Seems that the shell uses an integer value for background
options.background=1;
}
// TODO add more option checks here...
print("Inserting Key:", JSON.stringify(key),"Options:", JSON.stringify(options));
thedb[col].ensureIndex(key,options);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment