How to replace all occurance of a substring with another substring in MongoDB

Viewed 19
  1. I have a collection 'users' in the MongoDB.
  2. There is a field 'userCode' in the document as below
  ".id": "62ce200a550e190001c0f915",
  "userName": "John-den",
  "userCode": {
    "userName": "John-den",
    "description": {
      "userName": "John-den"
    }
  }
}
  1. I need to replace John by Smith for all the occurance. (Unfortunately I am using Mongo version 3.4.24).

I am able to replace parent userName as using and it is working as expected

db.getCollection("users").find({ "userName": /^John/ }).forEach(function(doc) {
    var updated_userName = doc.userName.replace(/John/ ,"Smith");

But since userCode is a field which stores JSON object (Type is string as checked in the Schema), I am not able to replace all occurances. It is just replacing first occurance, If going by above method.

1 Answers

You can do it with one query with $replaceAll Aggregation operator:

db.collection.update({},
[
  {
    "$set": {
      "userName": {
        "$replaceAll": {
          "input": "$userName",
          "find": "John",
          "replacement": "Naruto"
        }
      },
      "userCode.userName": {
        "$replaceAll": {
          "input": "$userName",
          "find": "John",
          "replacement": "Naruto"
        }
      },
      "userCode.description.userName": {
        "$replaceAll": {
          "input": "$userName",
          "find": "John",
          "replacement": "Naruto"
        }
      }
    }
  }
],
{
  multi: true
})

Working example

Related