How do I Replace Strings in MongoDB (With Example)

Replacing strings in MongoDB can be done using the $set operator. This operator can be used to set a value for a field in a document. An example of this would be to use the $set operator to replace a string in a document by using the syntax {$set: {fieldName: newString}}. This statement will update the fieldName field to the newString value.


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 .

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

x