2016-09-26 80 views
0

我有一个集合中有很多文档的MongoDB数据库。每篇文章都有一个名为myField的字段,其中包含一个字符串。MongoDB:更新所有文档中的字符串字段

是否有可能对我来说,运行集合中的所有文件批量更新,为每个文档修改的myField价值?

在我的情况下,我只想从每个字段中去掉尾随的“.html”。我在应用程序中使用node.js与Mongo进行交互,但我希望能够在mongo命令提示符下运行单个命令来执行此更新(如果可能的话)。

回答

1

尽可能使用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 :)'); 
+0

真棒,谢谢! – TW80000

+0

很高兴听到您的声音,欢迎您:) –

1

考虑使用bulkWrite API利用更新,因为它处理这个问题远比做一个循环内的更新即发送每次更新更好,更有效率对于大型数据集,每次迭代的请求可能会很慢。

bulkWrite API发送写入到服务器中说,500这给你一个更好的性能,你是不是在每500个请求发送每一个请求到服务器,只有一次的批次。

批量操作MongoDB的规定每批一个default internal limit of 1000作业等的500个文档的选择将是你有过批量大小,而不是让MongoDB的征收默认一些控制感好,即在规模较大的行动大于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) 
} 
相关问题