【问题标题】:Bulk create in Meteor在 Meteor 中批量创建
【发布时间】:2015-09-16 19:52:36
【问题描述】:

我需要在 Meteor 中一次创建 2000 个文档。我知道我可以使用

for (i=0; i<2000; i++) {
    CollectionName.insert({});
}

但我希望 Meteor 中有一个批量创建功能。如何以最快的方式插入这 2000 行?

【问题讨论】:

标签: javascript node.js mongodb meteor


【解决方案1】:

扩展@Akshat 的答案,这是适用于 Meteor 1.0+ 的语法

x = new Mongo.Collection("x");
var bulk = x.rawCollection().initializeUnorderedBulkOp();

bulk.insert( { _id: 1, item: "abc123", status: "A", soldQty: 5000 } );
bulk.insert( { _id: 2, item: "abc456", status: "A", soldQty: 150 } );
bulk.insert( { _id: 3, item: "abc789", status: "P", soldQty: 0 } );

Meteor.wrapAsync(bulk.execute)();

【讨论】:

  • 一件事让我大吃一惊:如果您有要插入的 ObjectID,则在插入原始集合时,您需要将它们转换为 Node 的 ObjectID 表示,而不是 Meteor 的表示。@987654322 @
  • 对我来说,它抛出了一个错误,然后我将上下文添加为第二个参数,所以它起作用了。 Meteor.wrapAsync(bulk.execute, bulk)();
【解决方案2】:

Meteor 本身并不支持这一点。但是,它确实使您可以访问节点 Mongodb 驱动程序,该驱动程序可以本机进行批量插入。

您只能在服务器上执行此操作:

var x = new Mongo.Collection("xxx");

x.rawCollection.insert([doc1, doc2, doc3...], function(err, result) {
    console.log(err, result)
});

或者如果您的 Meteor 实例可以访问 MongoDB 2.6:

var bulk = x.initializeUnorderedBulkOp();

bulk.insert( { _id: 1, item: "abc123", status: "A", soldQty: 5000 } );
bulk.insert( { _id: 2, item: "abc456", status: "A", soldQty: 150 } );
bulk.insert( { _id: 3, item: "abc789", status: "P", soldQty: 0 } );
bulk.execute( { w: "majority", wtimeout: 5000 } );

注意事项:

  • 这不是同步的,也不是在光纤中运行,因为它使用原始节点驱动程序。您需要使用 Meteor.bindEnvironment 或 Meteor.wrapAsync 来创建同步代码
  • 文档是无序插入的,可能与您添加它们时的原始顺序不同。
  • 如果您的实例未启用 oplog,Meteor 可能需要 10 秒才能通过发布方法“响应式”查看文档。

【讨论】:

    【解决方案3】:

    这是我使用的:

    /server/fixtures.js

    var insertIntoCollection = function(collection, dataArray){
      dataArray.forEach(function(item){
        collection.insert(item);
      });
    };
    
    if (Stuff.find().count() === 0) {
    
      var array = [
        { 
          // document1
        },{
          // document2
        }
      ];
    
      insertIntoCollection(Stuff, array);
    };
    

    【讨论】:

    • 简单的解决方案。 Meteor 1.4 将具有带有 Bulk Insert 的 Mongo 3.2。如果您没有 10,000 个文档,此解决方案将非常有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多