Skip to content

Instantly share code, notes, and snippets.

@rajiteh
Created February 18, 2016 17:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rajiteh/1680586300d11a9c9e7a to your computer and use it in GitHub Desktop.
Save rajiteh/1680586300d11a9c9e7a to your computer and use it in GitHub Desktop.
Recursively search and replace a string value across all collections in a mongodb database.
/*
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