0

I need to chage this:

userId: 'sdfsd'
pictures: ['https://stackoverflow.com/questions/ask.jpg', 'https://stackoverflow.com/questions/ask2.jpg']

To this:

userId: 'sdfsd'
pictures: ['ask.jpg', 'ask2.jpg']

Is there way to do it with just one command?

1
  • MongoDB version? Commented Mar 13, 2020 at 10:17

1 Answer 1

1

No need apply regex for your use case.

MongoDb way (v4.2)

We split by https://stackoverflow.com/questions/ or / and take last item.

db.collection.update({},
[
  {
    $set: {
      pictures: {
        $map: {
          input: "$pictures",
          in: {
            $arrayElemAt: [
              {
                $split: [
                  "$$this",
                  "https://stackoverflow.com/questions/" // or split by "/"
                ]
              },
              -1
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

JS way

We can apply regex, split, etc... and save individually.

db.collection.find({}).forEach(function(doc){
   doc.pictures = doc.pictures.map(x => x.replace("https://stackoverflow.com/questions/", ""));
   db.collection.save(doc);
})
Sign up to request clarification or add additional context in comments.

Comments

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.