[英]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.