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);
});
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With