Search code examples
javascriptmongodbmongodb-querymongodb-update

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 : House
   URL : www.home.com/600x600

I have already tried this but it doesn't seem to be working:

db.Paper.find({Name:"House"}).forEach(function(e,i) {
    e.URL=e.URL.replace("300","600");
    db.Paper.save(e);
});

Any ideas?


Solution

  • 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 ] }
                  ] 
              }
          }
        }
      ] 
    )