How to replace substring in MongoDB document?

In MongoDB, you can replace substrings in documents using JavaScript's replace() function within a forEach() loop. This approach finds documents, modifies the substring, and updates them back to the collection.

Sample Data

db.replaceSubstringDemo.insertOne({
    "WebsiteURL": "www.gogle.com"
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c76eaf21e9c5dd6f1f78276")
}

Let's verify the document was inserted ?

db.replaceSubstringDemo.find().pretty();
{
    "_id": ObjectId("5c76eaf21e9c5dd6f1f78276"),
    "WebsiteURL": "www.gogle.com"
}

Replace Substring Using forEach()

To replace "gogle" with "google" in the WebsiteURL field ?

db.replaceSubstringDemo.find({WebsiteURL: "www.gogle.com"}).forEach(function(url, k){
    url.WebsiteURL = url.WebsiteURL.replace("www.gogle.com", "www.google.com");
    db.replaceSubstringDemo.save(url);
});

Verify Result

db.replaceSubstringDemo.find().pretty();
{
    "_id": ObjectId("5c76eaf21e9c5dd6f1f78276"),
    "WebsiteURL": "www.google.com"
}

Alternative Method: Using updateMany()

For modern MongoDB versions, use aggregation pipeline with $set and $replaceOne ?

db.replaceSubstringDemo.updateMany(
    {},
    [{ $set: { WebsiteURL: { $replaceOne: { input: "$WebsiteURL", find: "gogle", replacement: "google" } } } }]
);

Conclusion

Use forEach() with JavaScript's replace() function for substring replacement in MongoDB documents. For newer versions, consider using $replaceOne in aggregation pipelines for better performance.

Updated on: 2026-03-14T23:57:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements