Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB regex replace

My table name is : table_video My field name in db is : url_value

Whose value is : http://192.168.1.124/test/abcd/abcd.m3u8

Value which is needed by me : http://192.168.1.124/test/abcd_NEW/abcd_NEW.m3u8

There are multiple values in place of "abcd", above url is just one example.

var cursor = db.table_video.find();
while (cursor.hasNext()) {
  var x = cursor.next();
  print("\n\n-----------------------------------");

  print("Before : url_value : "+x['url_value']);

  x['url_value'] = x['url_value'].replace(/^(.*?)\/test\/(.*?)\/(.*?)\.m3u8$/g, $1/test/$2_NEW/$2_NEW.m3u8);

  print("After : url_value : "+x['url_value']);

  db.table_video.update({_id : x._id}, x);

}

When I execute above command in mongo console, it gives an error : 2015-11-28T12:40:08.342+0530 ReferenceError: $1 is not defined

Any help is greatly appreciated

like image 539
gehlotparesh Avatar asked Oct 21 '25 03:10

gehlotparesh


1 Answers

Your regex is wrong you can get the expected result using this regex1.

But the best way to do this is using "bulk" operations for maximum efficiency.

var bulk = db.table_video.initializeUnorderedBulkOp();
var count = 0;
db.table_video.find().forEach(function(doc) {
    var newUrlValue = doc.url_value.replace(/^(.*?)\/test\/(.*?)\/(.*?)\.m3u8$/, '$1/test/$2_NEW/$3_NEW.m3u8');
    bulk.find( { '_id': doc._id } ).updateOne( { 
        '$set': { 'url_value': newUrlValue } 
    });
    count++;
    if (count % 100 === 0) {
        // Execute per 100 operation and re-init
        bulk.execute();
        bulk = db.table_video.initializeUnorderedBulkOp();
        count = 0;
    }
})

// Clean up queues
if (count > 0)  bulk.execute();

If your MongoDB version is older that 2.6 you need to use a while loop.

var cursor = db.table_video.find();
while (cursor.hasNext()) {
    var x = cursor.next();
    print("\n\n-----------------------------------");
    print("Before : url_value : "+x['url_value']);
    var newUrlValue = x['url_value'].replace(/^(.*?)\/test\/(.*?)\/(.*?)\.m3u8$/, '$1/test/$2_NEW/$2_NEW.m3u8');
    print("After : url_value : "+newUrlValue);
    db.table_video.update({ _id : x._id }, { '$set': { 'url_value': newUrlValue } } );

}

  1. Regex provided by @Uchiha.
like image 119
styvane Avatar answered Oct 23 '25 19:10

styvane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!