我有一個集合中有很多文檔的MongoDB數據庫。每篇文章都有一個名爲myField
的字段,其中包含一個字符串。MongoDB:更新所有文檔中的字符串字段
是否有可能對我來說,運行集合中的所有文件批量更新,爲每個文檔修改的myField
價值?
在我的情況下,我只想從每個字段中去掉尾隨的「.html」。我在應用程序中使用node.js與Mongo進行交互,但我希望能夠在mongo
命令提示符下運行單個命令來執行此更新(如果可能的話)。
我有一個集合中有很多文檔的MongoDB數據庫。每篇文章都有一個名爲myField
的字段,其中包含一個字符串。MongoDB:更新所有文檔中的字符串字段
是否有可能對我來說,運行集合中的所有文件批量更新,爲每個文檔修改的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的規定每批一個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)
}
真棒,謝謝! – TW80000
很高興聽到您的聲音,歡迎您:) –