1

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.

7
  • 1
    what is your MongoDB version ? Commented Apr 3, 2020 at 18:50
  • mongo version is 4.2.0 Commented Apr 3, 2020 at 18:53
  • Does this answer your question? How to replace substring in mongodb document Commented Apr 3, 2020 at 18:55
  • Nope, its the same that i tried myself Commented Apr 3, 2020 at 18:57
  • 1
    Since the doc that you pass to save does not have an _id it will create a new document in the collection. Was that the intent? Commented Apr 3, 2020 at 19:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

7 Comments

Mmm, isnt working. I think it could be because my doc is in the format of {"images":[...]} as opposed to "images":[...] ?
can you console.log(doc) and paste it here?
It might also be that you're not retrieving _id so if you want to update current docs then you have to get rid of _id: false
[object BSON] is the output
try printjson(doc)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.