'How to search and replace multiple instances of a string in an object/array in mongodb

I have around 100K documents in a collection where I'd need to replace various base URLs with another one, the documents/keys are not that structured and are very nested.

Very minimal example:

From this:

{
   "_id":"1232456",
   "params":{
      "url1":"https://www.asdf.com",
      "file1url":"https://1.asdf.com/thisfile.txt",
      "file2url":"https://1.asdf.com/thatfile.txt",
      "other":true
   },
   "otherurl":"https://1.asdf.com/example/",
   "other2":false
}

to this:

{
   "_id":"1232456",
   "params":{
      "url1":"https://www.test-asdf.com",
      "file1url":"https://1.test-asdf.com/thisfile.txt",
      "file2url":"https://1.test-asdf.com/thatfile.txt",
      "other":true
   },
   "otherurl":"https://1.test-asdf.com/example/",
   "other2":false
}

I'd usually replace a single key in mongodb compass with the mongosh with

db.mycol.updateMany(
  { url: { $regex: /asdf.com/ } },
  [{
    $set: { url: {
      $replaceOne: { input: "$url", find: "asdf.com", replacement: "test-asdf.com" }
    }}
  }]
)

but in the use case mentioned above I don't know all the keys and where they are located and if they are nested in an object ecc.

Is it possible to replace all occurrences of the baseurl in all documents?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source