Andres Julia
Andres Julia

Reputation: 91

Mongo - Replace substring of array

Im having trouble replacing a substring in some documents. This would be the example of one of the many similar documents:

{
"images" : [
    {
        "url" : "https://example/1234"
    },
    {
        "url" : "https://example/afaef"
    },
    {
        "url" : "https://example/abcdef"
    }
]}

I need to replace all the 'example' substrings for say 'newresult'

This is my approach

db.collection.find({'images.url':/.*example*/} , {'images.url':true, _id:false}).forEach(function(doc) {
doc.images.url = doc.images.url.replace('example', 'newresult');
db.collection.save(doc);});

However im getting many errors trying different forms of this like doc.images.url is undefined. Also tried some different yet still unsuccesful variations of this.

I would really appreciate some insights on what im doing wrong, or if theres a better way to do this. Thanks.

Upvotes: 1

Views: 414

Answers (1)

mickl
mickl

Reputation: 49945

You can try some MongoDB solution but if it's one-off JS script then you're close, the only thing you're missing is that images is an array so you need to use .map() like below:

let doc = {
"images" : [
    {
        "url" : "https://example/1234"
    },
    {
        "url" : "https://example/afaef"
    },
    {
        "url" : "https://example/abcdef"
    }
]};

doc.images= doc.images.map(({url, ...rest}) => ({url: url.replace('example', 'newresult'), ...rest}));

console.log(doc);

Upvotes: 2

Related Questions