Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a mongoDB collection with a field called "Url". There are many records in this collection. Inside this field, it always contains this text below:

"http://image-assets.s3.us-west-2.amazonaws.com/" For example "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg"

I would like to remove the portion of "http://image-assets.s3.us-west-2.amazonaws.com/", so the final result should look like "folder1/folder2/blah.jpg"

I would like to write a mongodb update statement, I don't know where to start. I can think of two things: (a) remove the first x number of characters, or (b) replace the text with a null. However the text includes a lot of slashes (/)

Your help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

This aggregation query with update on the result will work:

db.urls.aggregate( [ 
  { 
      $project: { 
          url: { 
              $split: [ 
                  "$url", 
                  "http://image-assets.s3.us-west-2.amazonaws.com/"
              ] 
          }
      }
  } 
] ).forEach( doc => db.urls.updateOne( { _id: doc._id }, { $set: { url: doc.url[1] } } )

With these two input documents:

{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg" }
{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah2.jpg" }

The updated url field will have values:

folder1/folder2/blah.jpg
folder1/folder2/blah2.jpg



[ EDIT ADD ]

Adding a check for url field with the URL string to be updated. Add this $match stage before the $project stage in the above aggregation query.

Note that in the regex search string ^ means "starts with", and the . (dot) is prefixed with a (backslash) so that it is considered as a dot only (not as regex meta-character).

  { 
      $match: { 
          url: { $regex: '^http://image-assets.s3.us-west-2.amazonaws.com/' } 
      } 
  }, 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...