How to update subset of a string in MongoDB?

独自空忆成欢 提交于 2020-01-25 08:03:13

问题


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?


回答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 ] }
              ] 
          }
      }
    }
  ] 
)



回答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/



来源:https://stackoverflow.com/questions/59462278/how-to-update-subset-of-a-string-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!