1

I need some help creating a monogdb query that removes the ending from specific URLs that contain the phrase '?=view'. For example three URLs are:

https://stackoverflow.com/questions/ask
https://stackoverflow.com/questions/ask100?=view
https://stackoverflow.com/questions/ask101

The output would be:

https://stackoverflow.com/questions/ask
https://stackoverflow.com/questions/ask100
https://stackoverflow.com/questions/ask101

Collection Example:

Product{
id: ...
URL: 'https://stackoverflow.com/questions/ask'}

Thanks in advance

Kingswoop
  • 148
  • 8
  • Possible duplicate of https://stackoverflow.com/questions/59462278/how-to-update-subset-of-a-string-in-mongodb/59462796#59462796 – krishna Prasad Jan 01 '20 at 12:09

3 Answers3

0

The following aggregation with update query strips the "?=view" from end of each string. The regex /.+\?=view$/ looks for strings that end with the sub-string "?=view".

db.test.aggregate( [
  {
       $match: { url: { $regex: /.+\?=view$/ } }
  },
  { 
      $addFields: { 
          url: { $split: [ "$url", "?" ] } 
      } 
  }
] ).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { url: doc.url[0] } } )
prasad_
  • 12,755
  • 2
  • 24
  • 36
0

Other solution is use $arrayElemAt after $split to take URL without query string.

db.Product.aggregate([
  {
    $project: {
      id: 1,
      URL: {
        $arrayElemAt: [
          {
            "$split": [
              "$URL",
              "?"
            ]
          },
          0
        ]
      }
    }
  }
])

MongoPlayground

Valijon
  • 12,667
  • 4
  • 34
  • 67
0

You can simply aggregate to find all the matching records with regex "/?=view" and the loop over to update it one by one as below:

> db.product.find()
{ "_id" : ObjectId("5e0c86a4a2e621133ea3b041"), "url" : "https://stackoverflow.com/questions/ask" }
{ "_id" : ObjectId("5e0c86b1a2e621133ea3b042"), "url" : "https://stackoverflow.com/questions/ask100?=view" }
{ "_id" : ObjectId("5e0c86c1a2e621133ea3b043"), "url" : "https://stackoverflow.com/questions/ask101" }
> 
> 
> db.product.aggregate( [   
{   $match: {            url: { $regex: "/?=view" } } }, 
{ $addFields: { url: { $split: [ "$url", "?" ] } } }
]).forEach(function(matchedDoc) {printjson(matchedDoc); 
    db.product.updateOne({_id: matchedDoc._id}, {$set: {url: matchedDoc.url[0]}  } )} 
)
{
    "_id" : ObjectId("5e0c86b1a2e621133ea3b042"),
    "url" : [
        "https://stackoverflow.com/questions/ask100",
        "=view"
    ]
}
> db.product.find()
{ "_id" : ObjectId("5e0c86a4a2e621133ea3b041"), "url" : "https://stackoverflow.com/questions/ask" }
{ "_id" : ObjectId("5e0c86b1a2e621133ea3b042"), "url" : "https://stackoverflow.com/questions/ask100" }
{ "_id" : ObjectId("5e0c86c1a2e621133ea3b043"), "url" : "https://stackoverflow.com/questions/ask101" }
>
krishna Prasad
  • 3,541
  • 1
  • 34
  • 44