MongoDB - How to replace url in field

86 views Asked by At

I have data as:

{ "_id" : ObjectId("64f029e54cfd5850f6c1a30f"), "pendek" : "test_123_456", "panjang" : "working tester mongodb", "landing_page" : "https://tester.com/", "user_page" : "https://iamold.web.app\n", "web_saya" : "https://yoootester.web.app" }

How to replace "iamold.web.app" with "iamnew.web.app"?

I am trying with this code not working:

db.web_saya.updateMany(
  { "user_page": { $regex: /iamold/ } },
  { $set: { "user_page": { $regexReplace: { input: "$user_page", find: /iamold/, replacement: "iamnew" } } } }
)

Thank you so much.

1

There are 1 answers

0
Yong Shun On

Don't think that the $regexReplace operator is valid. Probably you mean $replaceOne operator. Note that it is an operator for the aggregation pipeline. You need the update with aggregation pipeline in order to use it.

Note that this will replace the first found "iamold" word. In case you want to replace all the matching words, you should look for $replaceAll operator.

If you know the data pattern in which the user_page with "https://iamold.web.app\n" value needed to be updated, would recommend directly updating the value without regex.

db.web_saya.updateMany({
  "user_page": {
    $regex: "iamold"
  }
},
[
  {
    $set: {
      "user_page": {
        $replaceOne: {
          input: "$user_page",
          find: "iamold",
          replacement: "iamnew"
        }
      }
    }
  }
])

Or provide the value with domain URL will be more accurate.

db.web_saya.updateMany({
  "user_page": {
    $regex: "https://iamold.web.app"
  }
},
[
  {
    $set: {
      "user_page": {
        $replaceOne: {
          input: "$user_page",
          find: "https://iamold.web.app",
          replacement: "https://iamnew.web.app"
        }
      }
    }
  }
])

Demo @ Mongo Playground