- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }
Advertisements
To Continue Learning Please Login
Login with Google