[英]Mongodb - Updating large number of records every minute
有數百個傳感器每分鍾發送大約 100,000 條記錄。
所以我需要每分鍾通過 Api 捕獲並更新這些數據到 Nodejs + Mongodb 服務器。
現在這使服務器變得如此緩慢,以至於我無法檢索用於報告的數據。
甚至我的服務器 Web Url 也在不停地加載。
為了更新所有這些記錄,我現在在這台服務器上做的是:
for(var i = 0; i < records.length; i++) {
SensorData.update({storeId: records[i].id}, {$set: {inTime:records[i].inTime, outTime: records[i].outTime, timestamp: records[i].createdAt}});
}
此查詢處於循環狀態的原因是它更新了多個屬性的記錄,例如商店、建築、品牌、貨架等
任何人都可以幫助我最好的架構嗎?
最好的架構取決於您在設置中可以節省的資源(包括許多其他東西)。 如果您遇到緩慢,可能是系統資源(CPU、內存、網絡等)的限制。 因此,請監控 MongoDB 節點上的資源使用情況。
但是您可以使用insertMany或bulkWrite加速您對 MongoDB 的寫入(正如其他人所建議的那樣)。 insertMany
在一個 go 中寫入多個文檔,而bulkWrite
允許多個操作。
例如,您可以將文檔對象組合在一個數組中,然后使用insertMany
。 由於您的對象數組將存儲在 memory 中,因此您一次可以寫入多少個文檔取決於您的應用程序可用的 memory。
一個簡單的例子,比如,
let objArray = [];
for(var i = 0; i < records.length; i++) {
// add each doc to array
objArray.push({storeId: records[i].id}, {$set: {inTime:records[i].inTime, outTime: records[i].outTime, timestamp: records[i].createdAt}});
}
// using insertMany
db.collection(collectionName).insertMany(objArray, (err, res) => {
if (err) {
// handle error
}
if (res) {
// handle result
}
}
編輯:
由於您想要更新而不是插入,您可以嘗試使用updateMany ( bulkWrite
也允許您這樣做)。
// provide filters to match docs, or an empty object to match all i.e. {}
let matchThis = { field : {$eq : “abc” } };
// update matched docs
var toUpdate = { $set : {field : “xyz” } };
// make updates
db.collection(collectionName).updateMany(matchThis , toUpdate, (err , res) => {
// handle response
});
請注意,可用的系統資源在性能方面發揮着重要作用,即使是批量進行更新/寫入(然而,來回調用所花費的時間將大大減少)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.