Skip to content Skip to sidebar Skip to footer

How To Update Subset Of A String In MongoDB?

I want to update the following subset of a string in monogdb Collection: Paper Field: URL Document Current: Name : House URL : www.home.com/300x300 Document Updated Name

Solution 1:

You can use one of the following aggregations to query and update:

db.test.aggregate( [
  {
      $match: {
           url: { $regex: "300x300" }
      }
  },
  { 
      $addFields: { 
          url: { $split: [ "$url", "300" ] } 
      } 
  },
  { 
      $addFields: { 
          url: { 
              $concat: [ 
                        { $arrayElemAt: [ "$url", 0 ] }, 
                        "600", 
                        { $arrayElemAt: [ "$url", 1 ] }, 
                        "600", 
                        { $arrayElemAt: [ "$url", 2 ] }
              ] 
          }
      }
 }
] ).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { url: doc.url } } ) )


With MongoDB version 4.2+ you can specify the aggregation instead of an update operation with updateMany:

db.test.updateMany(
  { 
      url: { $regex: "300x300" }
  },
  [
    { 
      $addFields: { 
          url: { $split: [ "$url", "300" ] } 
      } 
    },
    { 
      $addFields: { 
          url: { 
              $concat: [ 
                        { $arrayElemAt: [ "$url", 0 ] }, 
                        "600", 
                        { $arrayElemAt: [ "$url", 1 ] }, 
                        "600", 
                        { $arrayElemAt: [ "$url", 2 ] }
              ] 
          }
      }
    }
  ] 
)

Solution 2:

Pretty simple, you have to use regex instead of string in the pattern of replace function as below:

> db.Paper.find({Name:"House"}).forEach(function (e, i) {e.URL =  e.URL.replace(/300/g, "600"), printjson(e); db.Paper.save(e);}  )
{
    "_id" : ObjectId("5e016224a16075c5bd26fbe2"),
    "Name" : "House",
    "URL" : "www.home.com/600x600"
}
> db.Paper.find()
{ "_id" : ObjectId("5e016224a16075c5bd26fbe2"), "Name" : "House", "URL" : "www.home.com/600x600" }
>

So, there is a difference between e.URL.replace("300", "600") and e.URL.replace(/300/g, "600"). You should figureout it yourself.

For references, please go through this: https://flaviocopes.com/how-to-replace-all-occurrences-string-javascript/


Post a Comment for "How To Update Subset Of A String In MongoDB?"