Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all matching substrings in mongodb

I need to replace all matching substring from all documents in a collection.

{ "content": "This is sample [/article] content.This is sample [/article] content." }

[/article] substring needs to be replaced with [/getting-started].

I have tried with the below code but it replaces only the first matches of string

 db.versions.find({}).forEach(function(e,i) {
    e.content=e.content.replace("/article1]","/getting-started]");
    db.versions.save(e);
});
like image 981
Rajesh Avatar asked Dec 11 '25 15:12

Rajesh


2 Answers

you can use replace regex matches as following

db.versions.find({}).forEach(function(e,i) {
    e.content=e.content.replace(/article\]/g,"getting-started]");
    db.versions.save(e);
});

result:

This is sample [/getting-started] content.This is sample [/getting-started] content.

like image 51
Ahmed Yousif Avatar answered Dec 13 '25 04:12

Ahmed Yousif


Try the power of regex to run through the document till end

db.versions.find({}).forEach(function(e,i) {
    var find = "//article";
    var re = new RegExp(find, 'g');
    e.content = e.content.replace(re,"//getting-started");
    db.versions.save(e);
});
like image 30
Pandiyan Cool Avatar answered Dec 13 '25 05:12

Pandiyan Cool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!