How to Replace Strings in MongoDB (With Example)


You can use the following syntax to replace a specific string in a field in MongoDB:

db.myCollection.updateMany(
  { fieldName: { $regex: /old/ } },
  [{
    $set: { fieldName: {
      $replaceOne: { input: "$fieldName", find: "old", replacement: "new" }
    }}
  }]
)

This particular example replaces the string “old” with “new” in the field titled “fieldName” within the collection titled myCollection.

The following example shows how to use this syntax in practice with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", conference: "Western", points: 31})
db.teams.insertOne({team: "Spurs", conference: "Western", points: 22})
db.teams.insertOne({team: "Rockets", conference: "Western", points: 19})
db.teams.insertOne({team: "Celtics", conference: "Eastern", points: 26})
db.teams.insertOne({team: "Cavs", conference: "Eastern", points: 33})
db.teams.insertOne({team: "Nets", conference: "Eastern", points: 38})

Example: Replace String in MongoDB

We can use the following code to replace the string “Western” with “West” in the conference field:

db.teams.updateMany(
  { conference: { $regex: /Western/ } },
  [{
    $set: { conference: {
      $replaceOne: { input: "$conference", find: "Western", replacement: "West" }
    }}
  }]
)

Here’s what the updated collection now looks like:

{ _id: ObjectId("620139494cb04b772fd7a8fa"),
  team: 'Mavs',
  conference: 'West',
  points: 31 }
{ _id: ObjectId("620139494cb04b772fd7a8fb"),
  team: 'Spurs',
  conference: 'West',
  points: 22 }
{ _id: ObjectId("620139494cb04b772fd7a8fc"),
  team: 'Rockets',
  conference: 'West',
  points: 19 }
{ _id: ObjectId("620139494cb04b772fd7a8fd"),
  team: 'Celtics',
  conference: 'Eastern',
  points: 26 }
{ _id: ObjectId("620139494cb04b772fd7a8fe"),
  team: 'Cavs',
  conference: 'Eastern',
  points: 33 }
{ _id: ObjectId("620139494cb04b772fd7a8ff"),
  team: 'Nets',
  conference: 'Eastern',
  points: 38 } 

Notice that every document that had the string “Western” in the conference field now has “West” in the conference field.

Any document that did not have the string “Western” in the conference field simply kept their original string.

Note: You can find the complete documentation for the $replaceOne function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Check if Field Contains a String
MongoDB: How to Add a New Field
MongoDB: How to Remove a Field

Leave a Reply

Your email address will not be published.