[英]In Meteor - how to do a bulk insert into a nested array
我正在嘗試將數千條記錄導入流星集合中的嵌套數組中。 這是來自JSON對象的財務數據。 在插入之前,我需要對其進行一些計算,因此無法進行原始處理。 每次寫入都執行$ addToSet操作非常非常慢。 有沒有辦法在一個呼叫中推送全部數據?
我的架構看起來像這樣。
NestedSchema = new SimpleSchema({
item: {
type: String
},
aThing: {
type: Number
}
});
MasterSchema = new SimpleSchema({
symbol: {
type: String,
label: 'Symbol',
unique: true
},
data: {
type: [NestedSchema],
optional: true
}
});
我有一堆想要插入的數據。
var dataToInsert = [{item: "thing", aThing: 1}, {item: "thing2", aThing: 2}, {item: "thing3", aThing: 2}];
我要插入嵌套數組的數據是5000多個記錄。 我看過https://atmospherejs.com/udondan/bulk-collection-update和https://atmospherejs.com/mikowals/batch-insert,但它們似乎並沒有完全滿足我的要求。 理想情況下,我將有一個解決方案,可以在收集新記錄時批量添加新記錄。
您可以使用數組上的forEach()
方法更新集合,並在循環內利用寫命令Bulk API的優勢,該API允許執行批量更新操作,這些操作只是服務器頂部的抽象,因此易於實現建立批量操作。 這些批量操作主要有兩個方面:
請注意,對於低於2.6的舊服務器,API將下轉換操作。 但是,不可能將100%下變頻,因此在某些極端情況下無法正確報告正確的數字。 您可以打通收集和數據庫對象的原始訪問在故宮的MongoDB驅動rawCollection
和rawDatabase
上的方法Mongo.Collection
MyCollection = new Meteor.Collection("mycollection");
if (Meteor.isServer) {
Meteor.startup(function () {
Meteor.methods({
insertData: function(symbol) {
var bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp(),
counter = 0,
dataToInsert = [...];
dataToInsert.forEach(function(data) {
bulkOp.find({"symbol": symbol}).updateOne({ "$addToSet": data });
counter++;
if (counter % 1000 == 0) {
// Execute per 1000 operations and re-initialize every 1000 update statements
bulkOp.execute(function(e, result) {
// do something with result
console.info('result.nMatched', result.nMatched, 'result.nModified', result.nModified);
});
bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp();
}
});
// Clean up queues
if (counter % 1000 != 0){
bulkOp.execute(function(e, result) {
// do something with result
});
}
}
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.