Search and Replace mongodb database

2

I have several collections in mongodb and I would like to do a "search / replace" for all collections and for each field that is string "http:" replace with "https:"

Example:

var object = {
    "_id" : ObjectId("58e7c7a5b03d4641f2aad7bb"),
    "t1" : "Exemplo 1 http:// ocorrencia",
    "t2" : "Exemplo 12  silva  service souza encontrado na url http://192.22.11.102:8080",
    "image" : [ 
        {
            "image_id" : ObjectId("58e2e041a4c8023a35a4260e"),
            "blog" : "http://10.11.12.23"
        }, 
        {
            "blog" : "http://10.11.12.23"
        }
    ],
    "tr" : {
        "ts" : "Maria Santanta",
        "message" : "http://message"
    },
   "date" : "2016-02-25T20:39:26.084Z"
}

I was able to replace all occurrences using:

var string = JSON.stringify(object)
string = string.replace(/http:/g,"https:")

The problem is to convert back to json object because it does not recognize ObjectId, ISODate among others.

I tried to use JSON.parse(string) unsuccessful

    
asked by anonymous 11.04.2017 / 19:05

1 answer

1

Resolve recursively, passing through each element and replacing it.

function iterate(obj, stack) {
for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        if (typeof obj[property] == "object") {
            iterate(obj[property], stack + '.' + property);
        } else {
            if(typeof obj[property] == 'string'){
               obj[property] = obj[property].replace(/http:/g,"https:");

            }
        }
    }
}
return obj;
}
db.getCollectionNames().forEach(function(collection){
    var cursor = db.getCollection(collection).find();
       while (cursor.hasNext()) {
          var x = cursor.next();
          x = iterate(x, '')
         db.getCollection(collection).update({"_id" : x._id}, x);
     }
});
    
11.04.2017 / 20:34