How to replace string in all documents in Mongo

后端 未结 4 1770
长发绾君心
长发绾君心 2020-12-13 14:52

I need to replace a string in certain documents. I have googled this code, but it unfortunately does not change anything. I am not sure about the syntax on the line bellow:<

4条回答
  •  [愿得一人]
    2020-12-13 15:15

    The best way to do this if you are on MongoDB 2.6 or newer is looping over the cursor object using the .forEach method and update each document usin "bulk" operations for maximum efficiency.

    var bulk = db.collection.initializeOrderedBulkOp();
    var count = 0;
    
    db.collection.find().forEach(function(doc) {
        print("Before: "+doc.source.url);
        bulk.find({ '_id': doc._id }).update({
            '$set': { 'source.url': doc.source.url.replace('aaa', 'bbb') }
        })
        count++;
        if(count % 200 === 0) {
            bulk.execute();
            bulk = db.collection.initializeOrderedBulkOp();
        }
    
    // Clean up queues
    if (count > 0) 
        bulk.execute();
    

    From MongoDB 3.2 the Bulk() API and its associated methods are deprecated you will need to use the db.collection.bulkWrite() method.

    You will need loop over the cursor, build your query dynamically and $push each operation to an array.

    var operations = [];
    db.collection.find().forEach(function(doc) {
        print("Before: "+doc.source.url);
        var operation = {
            updateOne: { 
                filter: { '_id': doc._id }, 
                update: { 
                    '$set': { 'source.url': doc.source.url.replace('aaa', 'bbb') }
                }
            }
        };
        operations.push(operation);
    })
    operations.push({ 
        ordered: true, 
        writeConcern: { w: "majority", wtimeout: 5000 } 
    })
    
    db.collection.bulkWrite(operations);
    

提交回复
热议问题