Search and replace mongodb database

Asked

Viewed 113 times

2

I have several collections in mongodb and would like to do a "search/replace" for all collections and for each field that is the 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 override all the occurrences using:

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

The problem is to convert back to json object as it does not recognize Objectid, Isodate among others.

I tried to use JSON.parse(string) unsuccessful

1 answer

1


Be able to solve recursively, passing through each element and replacing.

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);
     }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.