Home > OS >  UpdateOne with a Regex MongoDB
UpdateOne with a Regex MongoDB

Time:06-07

I need to replace a portion of string in a collection. I found this answer https://stackoverflow.com/a/60353546/11904736 but I got this error when I try it :

Error: the update operation document must contain atomic operators

So I believe I'm pretty close with the ReplaceOne operator, got no error, but the string I'm searching does not change. I must find every /mordu/episodes/ and replace with /mordu/webseries/ in all the collection for CanonicalWebLink property :

db.mycollections.replaceOne(
   { "CanonicalWebLink": { $regex: "/mordu/\//episodes/" } },
   { "CanonicalWebLink": "/mordu/webseries/"})

Does anyone can explain why this code does not work as I would expect ? CanonicalWebLink is a URL like that : "http://mywebsite/mordu/episodes/2/some-page-slug"

CodePudding user response:

Since mongoDB version 4.4 you can use $replaceAll:

db.collection.update({
  CanonicalWebLink: {
    $regex: "/mordu/episodes/"
  }
},
[
  {
    $set: {
      CanonicalWebLink: {
        $replaceAll: {
          input: "$CanonicalWebLink",
          find: "/mordu/episodes/",
          replacement: "/mordu/webseries/"
        }
      }
    }
  }
],
{
  multi: true
})

Playground example v 4.4

For mongoDB version 4.2 (as you can see here answer by @Xavier Guihot):

db.collection.update({
  CanonicalWebLink: {$regex: "/mordu/episodes/"}
},
[
  {
    $set: {
      CanonicalWebLink: {
        $concat: [
          {
            $arrayElemAt: [
              {$split: ["$CanonicalWebLink", "/mordu/episodes/"]},
              0
            ]
          },
          "/mordu/webseries/",
          {
            $arrayElemAt: [
              {$split: ["$CanonicalWebLink", "/mordu/episodes/"]},
              1
            ]
          }
        ]
      }
    }
  }
],
{
  multi: true
})

Playground example v 4.2

  • Related