Mongodb Replace a word from a string

So I have a mongodb document that has a field like this

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

I want to replace the scale in the string with another text so that:

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

Can this be done?

+4
source share
2 answers

You can use the mongo cursor method to perform atomic updates using the operator: forEach() $set

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 the very large collection for updating, you can speed things up a bit and restructure your update operations to be sent in bulk, like: bulkWrite

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);
+6
source
db.myCollection.update({image: 'http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg'}, {$set: {image : 'http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg'}})

, . . : MongoDB:

0

Source: https://habr.com/ru/post/1584609/


All Articles