bekanur98
bekanur98

Reputation: 520

Mongodb, update part of string with regex in one query

How to substitute part of string in mongodb with update query.

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 have no idea how to substitute part of string

Upvotes: 3

Views: 1243

Answers (1)

R2D2
R2D2

Reputation: 10697

Maybe like this:

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

Explained:

  1. match all documents having test.com in the uri field.

  2. Use aggregation pipeline to update the matching part to the expected

  3. Use multi:true to update all such documents

Playground

Upvotes: 2

Related Questions