I need to replace a string in certain documents. I have googled this code, but it unfortunately does not change anything. I am not sure about the syntax on the line bellow:<
Nowadays,
Mongo 4.2, db.collection.updateMany (alias of db.collection.update) can accept an aggregation pipeline, finally allowing the update of a field based on its own value.Mongo 4.4, the new aggregation operator $replaceOne makes it very easy to replace part of a string.// { "source" : { "url" : "http://aaa/xxx/yyy" } }
// { "source" : { "url" : "http://eee/xxx/yyy" } }
db.collection.updateMany(
{ "source.url": { $regex: /aaa/ } },
[{
$set: { "source.url": {
$replaceOne: { input: "$source.url", find: "aaa", replacement: "bbb" }
}}
}]
)
// { "source" : { "url" : "http://bbb/xxx/yyy" } }
// { "source" : { "url" : "http://eee/xxx/yyy" } }
{ "source.url": { $regex: /aaa/ } }) is the match query, filtering which documents to update (the ones containing "aaa")$set: { "source.url": {...) is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):
Mongo 4.2) which in this case replaces the value of a field.source.url is modified directly based on the its own value ($source.url).Note that this is fully handled server side which won't allow you to perform the debug printing part of your question.