How to replace string in all documents in Mongo

后端 未结 4 1775
长发绾君心
长发绾君心 2020-12-13 14:52

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:<

4条回答
  •  心在旅途
    2020-12-13 15:13

    Nowadays,

    • starting 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.
    • starting 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" } }
    
    • The first part ({ "source.url": { $regex: /aaa/ } }) is the match query, filtering which documents to update (the ones containing "aaa")
    • The second part ($set: { "source.url": {...) is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):
      • $set is a new aggregation operator (Mongo 4.2) which in this case replaces the value of a field.
      • The new value is computed with the new $replaceOne operator. Note how 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.

提交回复
热议问题