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
CodePudding user response:
Maybe like this:
db.collection.update({
"url": {
"$regex": "test.com"
}
},
[
{
"$set": {
"url": {
"$replaceAll": {
"input": "$url",
"find": "test.com",
"replacement": "example.com"
}
}
}
}
],
{
"multi": true
})
Explained:
match all documents having test.com in the uri field.
Use aggregation pipeline to update the matching part to the expected
Use multi:true to update all such documents