ksav
ksav

Reputation: 20840

mongodb - find and replace partial string across various fields

Say I have a URL: aaa.something.com/id that is found in several collections, in many different fields.

I would like to change it to bbb.something.com/id via regex (or similar) to find and replace only the prefix of the URL string.

The following:

db.tests.find({ "url": /^aaa\.something\.com\// }).forEach(function(doc) {
    doc.url = doc.url.replace(/^aaa\.something\.com\//, "bbb.something.com/");
    db.tests.update({ "_id": doc._id },{ "$set": { "url": doc.name } });
});

assumes that the field is always known to be url.

But in the database, The URL could be found in a number of locations such as:

Upvotes: 2

Views: 301

Answers (1)

hyades
hyades

Reputation: 3170

You can a wildcard text index and then use $text to find documents which match the specified regex. Once you get these docs you can write Javascript code for finding keys which match your regex and replacing them as needed.

Upvotes: 1

Related Questions