How to replace substring in MongoDB document?


In order to replace substring in MongoDB document, you can use the replace() function. To understand it further, let us create a collection with document. The query to create a collection with document is as follows −

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

Display all documents from a collection with the help of find() method. The query is as follows −

> db.replaceSubstringDemo.find().pretty();

Output

{
   "_id" : ObjectId("5c76eaf21e9c5dd6f1f78276"),
   "WebsiteURL" : "www.gogle.com"
}

Here is the query to replace substring in MongoDB document −

> 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)
   ... });

Let us display the document from a collection once again to verify the replacement has been done or not. The query is as follows −

> db.replaceSubstringDemo.find().pretty();

Output

{
   "_id" : ObjectId("5c76eaf21e9c5dd6f1f78276"),
   "WebsiteURL" : "www.google.com"
}

Updated on: 30-Jul-2019

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements