Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a word from a string

I have mongodb documents with a field like this:

Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg

How can I replace the zoom part in the string value with some other text in order to get:

Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg
like image 662
Sameer Shaikh Avatar asked Apr 25 '15 07:04

Sameer Shaikh


1 Answers

You could use mongo's forEach() cursor method to do an atomic update with the $set operator :

db.collection.find({}).snapshot().forEach(function(doc) {
    var updated_url = doc.Image.replace('zoom', 'product2');
    db.collection.update(
        {"_id": doc._id}, 
        { "$set": { "Image": updated_url } }
    );
});

Given a very large collection to update, you could speed up things a little bit with bulkWrite and restructure your update operations to be sent in bulk as:

var ops = [];
db.collection.find({}).snapshot().forEach(function(doc) {
    ops.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "Image": doc.Image.replace('zoom', 'product2') } }
        }
    });

    if ( ops.length === 500 ) {
        db.collection.bulkWrite(ops);
        ops = [];
    }
})

if ( ops.length > 0 )  
    db.collection.bulkWrite(ops);
like image 176
chridam Avatar answered Sep 22 '22 12:09

chridam