Forked from rajiteh/mongo_search_and_replace.js
Last active
December 21, 2020 20:43
-
-
Save vonox7/9fd5054ad9fcbf39d6c1071800647b7b to your computer and use it in GitHub Desktop.
Recursive MongoDB fulltext deep string replacement migration
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 & updated objects | |
| 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) { | |
| if (DEBUG) { | |
| print("Updated ===> " + collections[i] + "(" + items._id + ")"); | |
| } | |
| db[collections[i]].save(items); | |
| } | |
| }); | |
| path.pop(); | |
| } | |
| }; | |
| recursiveReplace('https://oldurl', 'https://newurl'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment