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.
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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With