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

3
我有一个MongoDB数据库,其中包含许多集合中的文档。每篇文章都有一个称为myField的字段,其中包含一个字符串。
是否可以对集合中的所有文档运行批量更新,修改每个文档的myField值?
在我的情况下,我只想从每个字段中剥离掉结尾的“.html”。我正在使用node.js与Mongo交互,但如果可能的话,我更喜欢能够在mongo命令提示符上运行单个命令来执行此更新。
2个回答

5

可以使用命令提示符使用 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 :)');

3
考虑使用bulkWrite API来利用更新,因为它比在循环内做更新更好、更有效。例如,对于大型数据集,每次迭代发送每个更新请求可能会很慢。 bulkWrite API将写入操作按批次(例如500个)发送到服务器,这样可以获得更高的性能,因为您不需要将每个请求都发送到服务器,只需每500个请求发送一次即可。
对于批量操作,MongoDB对每批操作实施了默认的内部限制为1000个操作,因此对于大于1000个文档的较大操作,选择500个文档将是一个不错的选择,因为这样可以对批处理大小进行一定程度的控制,而不是让MongoDB强制执行默认值。
请参考以下示例:
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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接