Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Replace all the same words in mongoDB using REGEX

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")"
  }
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!