Home > Software design >  Replace all the same words in mongoDB using REGEX
Replace all the same words in mongoDB using REGEX

Time:09-16

Im trying, in mongoDB using mongosh,to replace all the words that i select in a collection for others.

Example, I have this:

_id:12345678901
name:"Peter Parker"
profession:"Superhero"

_id:12345678902
name:"Peter Parker"
profession:"Journalist"

_id:12345678902
name:"Hulk"
profession:"Software Developer"

And I want to replace all the "Peter Parker" with "Superman" in a collection called "firstList" to get this:

_id:12345678901
name:"Superman"
profession:"Superhero"

_id:12345678902
name:"Superman"
profession:"Journalist"

_id:12345678902
name:"Hulk"
profession:"Software Developer"

Im trying this, but it doesnt work:

db.firstList.replace({
  "name": {
    "$regex": "(/( |^)Peter Parker\b/g, "$Superman")"
  }
})

CodePudding user response:

According to your data you don't need regex, you can use the word into find stage as it is.

You can use an aggregation query into update using [] like this:

db.collection.update({
  "name": {
    "$regex": "Peter Parker"
  }
},
[
  {
    "$set": {
      "name": {
        "$replaceAll": {
          "input": "$name",
          "find": "Peter Parker",
          "replacement": "Superman"
        }
      }
    }
  }
],
{
  "multi": true
})

Example here

By the way, you can use the regex into find object if you want. But if you want to match the entire word "Peter Parker" you can use without regex.

  • Related