Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace a string in an array in Mongo

Tags:

mongodb

I have the following data structure in Mongo which I want to edit:

{
   "images" : [{
      "image_id" : 46456,
      "image_path" : "http://cdn.site.com/image.jpg",
      "image_thumbnail" : "http://cdn.site.com/image.jpg",
      "image_detailed" : "http://cdn.site.com/image.jpg",
      "image_type" : "0"
    }, {
      "image_id" : 46452,
      "image_path" : "http://cdn.site.com/image.jpg",
      "image_thumbnail" : "http://cdn.site.com/image.jpg",
      "image_detailed" : "http://cdn.site.com/image.jpg",
      "image_type" : "2"
    }, {
      "image_id" : 46453,
      "image_path" : "http://cdn.site.com/image.jpg",
      "image_thumbnail" : "http://cdn.site.com/image.jpg",
      "image_detailed" : "http://cdn.site.com/image.jpg",
      "image_type" : "0"
    }, {
      "image_id" : 46454,
      "image_path" : "http://cdn.site.com/image.jpg",
      "image_thumbnail" : "http://cdn.site.com/image.jpg",
      "image_detailed" : "http://cdn.site.com/image.jpg",
      "image_type" : "A"
    }]
}

I would like to replace all the 'http' in the entire array to 'https' regardless which field they are in.

How do I do so ?

Thanks.

like image 527
thotheolh Avatar asked Oct 11 '13 05:10

thotheolh


People also ask

How do you replace a section of a string in MongoDB?

MongoDB 4.4 introduced nine new aggregation pipeline operators, including two new operators for finding and replacing a substring. The two new operators that allow you to find and replace a substring are the $replaceOne and $replaceAll operators.

How do you update an array element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I search an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

There is no built-in functionality in MongoDB. You can replace all the http with https by looping all records. In the Mongo shell you can do it as follows :

String.prototype.replaceAll=function(s1, s2) {return this.split(s1).join(s2)}

var cursor = db.myCollection.find({},{_id:0});
while(cursor.hasNext()) {
    var obj = cursor.next();
    var objStr = JSON.stringify(obj);
    var newObjStr = objStr.replaceAll("http","https");
    db.myCollection.update(obj,JSON.parse(newObjStr));
}
like image 175
Parvin Gasimzade Avatar answered Sep 29 '22 17:09

Parvin Gasimzade