簡體   English   中英

MongoDB:更新所有文檔中的字符串字段

[英]MongoDB: Update a string field in all documents

我有一個MongoDB數據庫,其中包含許多文檔。 這些文章每個都有一個名為myField的字段,其中包含一個字符串。

我可以對集合中的所有文檔進行批量更新,為每個文檔修改myField的值嗎?

就我而言,我只想從每個字段中刪除尾隨的“ .html”。 我正在使用node.js與我的應用程序中的Mongo進行交互,但我更希望能夠在mongo命令提示符下運行單個命令來進行此更新。

是的,可以使用mongo從命令提示符更新mongoDB文檔信息。

說出腳本文件名稱migration.js並轉到該文件目錄,然后打開命令提示符並運行此命令。

mongo localhost/dbName migration.js

migration.js代碼類似:

print('Please wait it may will take some time to complete migration');
print('....');

db.collectionName.find().forEach( function(doc) {

    if(!doc._id) {
        print('No doc found');
        return;
    }
    // if need can apply logic to update myField

    db.collectionName.update({_id: doc._id}, {$set: {myField: "newVale"}});
});

print('Migration has been completed :)');

考慮使用bulkWrite API來利用更新,因為它比在循環中進行更新要好得多,效率更高,例如,對於大型數據集,每次迭代發送每個更新請求可能會很慢。

bulkWrite API將批量寫入發送到服務器,例如500,這將為您帶來更好的性能,因為您不會將每個請求發送到服務器,而是每500個請求中只有一次。

對於批量操作,MongoDB對每個批次施加默認的內部限制,即1000個操作,因此從可以控制批量大小的角度控制而不是讓MongoDB施加默認值的情況下,最好選擇500個文檔,即對於較大的操作。數量大於1000個文檔。

請看以下示例:

var bulkUpdateOps = [], // create an array to hold the update operations
    counter = 0, // counter to control the batch sizes
    rgx = /\.(html)$/i, // regex for querying and updating the field
    cursor = db.collection.find({ "myField": rgx }); // cursor for iterating

cursor.snapshot().forEach(function(doc) {
    var updatedField = doc.myField.replace(rgx, ''); // update field
    bulkUpdateOps.push({ // queue the update operations to an array
        "updateOne": {
            "filter": { 
                "_id": doc._id, 
                "myField": { "$ne": updatedField } 
            },
            "update": { "$set": { "myField": updatedField } }
        }
    });
    counter++;

    if (counter % 500 == 0) { // send the update ops in bulk
        db.collection.bulkWrite(bulkUpdateOps);
        bulkUpdateOps = []; // reset the array
    }
})

if (counter % 500 != 0) { // clean up remaining operations in the queue
    db.collection.bulkWrite(bulkUpdateOps)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM