Rajesh
Rajesh

Reputation: 303

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

Upvotes: 3

Views: 332

Answers (2)

Pandiyan Cool
Pandiyan Cool

Reputation: 6585

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

Upvotes: 2

Ahmed Yousif
Ahmed Yousif

Reputation: 2348

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.

Upvotes: 2

Related Questions