-
-
Save piemme/829550231c968999c9cf7dcaf62a0c87 to your computer and use it in GitHub Desktop.
Recursively search and replace a string value across all collections in a mongodb database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Recursively traverses all collections and objects/arrays contained within documents replacing every | |
instance of 'find' with 'replace'. | |
mongo <db_name> mongo_search_and_replace.js | |
*/ | |
function escapeRegExp(str) { | |
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); | |
} | |
var recursiveReplace = function(find, replace) { | |
var DEBUG = false; // Set this to true to find out paths | |
var collections = db.getCollectionNames(); | |
var path = [] | |
for (var i in collections) { | |
path.push(collections[i]) | |
db[collections[i]].find().forEach(function(items) { | |
var isDirty = false; | |
var recursiveFunc = function(itemsArray, itemKey) { | |
path.push(itemKey) | |
var isDirty = false; | |
var itemValue = itemsArray[itemKey]; | |
if ((typeof itemValue === 'string' || itemValue instanceof String) && | |
itemValue.indexOf(find) > -1) { | |
itemsArray[itemKey] = itemsArray[itemKey].replace(new RegExp(escapeRegExp(find),"g"), replace); | |
if DEBUG: | |
print(path) | |
isDirty = true; | |
} else if(itemValue != null && typeof itemValue === "object") { | |
Object.keys(itemValue).forEach(function (itemValueKey) { | |
isDirty = recursiveFunc(itemValue, itemValueKey) || isDirty; | |
}); | |
} | |
path.pop() | |
return isDirty; | |
}; | |
Object.keys(items).forEach(function (item) { | |
isDirty = recursiveFunc(items, item) || isDirty; | |
}); | |
if (isDirty) { | |
print("Updated ===> " + collections[i] + "(" + items._id + ")"); | |
db[collections[i]].save(items) | |
} | |
}); | |
path.pop() | |
}; | |
}; | |
/* recursiveReplace('{{ search_str }}', '{{ replace_str }}') */ | |
recursiveReplace('http://docker', 'http://kekker') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment