0

How to substitute part of the string in MongoDB with an update query.

For example, I have this:

_id: 123
url:"test.com?from_user=1"
name:"Superhero"

_id:124
url:"regex.com?from_user=3"
name:"Journalist"

_id:123
url:"test.com?from_user=2"
name:"Software Developer"

And I want to substitute all documents with _id:123 part of url = "test.com" to "sample.com" to get this:

_id: 123
url:"sample.com?from_user=1"
name:"Superhero"

_id:124
url:"regex.com?from_user=3"
name:"Journalist"

_id:123
url:"sample.com?from_user=2"
name:"Software Developer"

I tried this way

$collection->updateMany([
     '_id' => 123,
     'url' => [
          '$regex' => "test.com"
      ]
], [
     '$set' => [
          "url" => [
               '$replaceAll' => [
                    "input" => '$url',
                    "find" => "test.com",
                    "replacement" => "example.com"
                ]
           ]
     ]
], [
     'multi' => true
])

But here it displays an error:

The dollar ($) prefixed field '$replaceAll' in 'url.$replaceAll' is not valid for storage.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
bekanur98
  • 502
  • 1
  • 7
  • 20

1 Answers1

1

Your update query requires the aggregation pipeline.

db.collection.update({
  "_id": 123,
  "url": {
    "$regex": "test.com"
  }
},
[
  {
    "$set": {
      "url": {
        "$replaceAll": {
          "input": "$url",
          "find": "test.com",
          "replacement": "example.com"
        }
      }
    }
  }
],
{
  multi: true
})

Demo @ MongoDB Playground

Not a PHP developer, you need to pass the newObj param as an array:

$collection->updateMany([
     '_id' => 123,
     'url' => [
          '$regex' => "test.com"
      ]
], array([
     '$set' => [
          "url" => [
               '$replaceAll' => [
                    "input" => '$url',
                    "find" => "test.com",
                    "replacement" => "example.com"
                ]
           ]
     ]
]), [
     'multi' => true
])

Note that: _id field is unique identifier in MongoDB document, it is not possible to have the documents with duplicate _id.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 1
    yes, your are right, that MongoDB documents does not have duplicate _id, it was just a example, you can imagine that it is client_id – bekanur98 Dec 05 '22 at 05:07