MongoDB replace substring in field

Many times you will find yourself needing to do a MongoDB replace in a text field of a MongoDB collection. This can be a frustrating exercise as the syntax is not so straightforward. There are generally two conditions that you will likely need to replace the data in a field –>

  1. Where you just want to query the field and change the text.
  2. Permanently changing the text in all fields.

For the first case of just doing a query and changing the text, but not changing the text in your collection, you will use the aggregate method. For example, let’s use a complex query where we forgot to prefix all of our <a href=”/every-path”> with the domain. We do that with the following syntax[
         item: { $replaceAll: { input: "$description", find: "href=\"\/", replacement: "target=\"city\" href=\"https:\/\/\/" } }

This will change every “description” field in the “city” collection from <a href=”/some-path”> with <a target=”city” href=””>. Again, this is a query only, no data in the database itself is changed.

Now suppose, we want to permanently change every instance of the field. We accomplish this using MongoDB’s updateMany and replaceAll:
    {description: {$regex: /href=\"\//}},
        $set: {description: {
            $replaceAll: {input: "$description", find: "href=\"\/", replacement: "target=\"city\" href=\"https:\/\/\/" }

This will permanently replace every <a href=”/every-path”> with <a target=”city” href=””> with the fully-qualified domain name (FQDN).

Try it for yourself and all the best on your MongoDB updates!

For can find additional information on MongoDB here on, or by going directly to replaceAll at MongoDB, or here for the usage of updateMany.