简体   繁体   English

在 Meteor 中批量创建

[英]Bulk create in Meteor

I need to create 2000 documents at once in Meteor.我需要在 Meteor 中一次创建 2000 个文档。 I know I can use我知道我可以使用

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

but I hope there is a bulk create function in Meteor.但我希望 Meteor 中有一个批量创建功能。 How can I insert these 2000 rows in the fastest way possible?如何以最快的方式插入这 2000 行?

Meteor doesn't natively support this. Meteor 本身并不支持这一点。 However, it does give you access to the node Mongodb driver which can natively do a bulk insert.但是,它确实让您可以访问节点 Mongodb 驱动程序,该驱动程序本身可以进行批量插入。

You can only do this on the server:您只能在服务器上执行此操作:

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

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

Or with MongoDB 2.6 if your Meteor instance has access to it:或者使用 MongoDB 2.6,如果您的 Meteor 实例可以访问它:

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 } );

Notes:笔记:

  • This is not synchronous or isn't run in a fiber as it uses the raw node driver.这不是同步的,也不是在光纤中运行,因为它使用原始节点驱动程序。 You need to use Meteor.bindEnvironment or Meteor.wrapAsync to create synchronous code您需要使用 Meteor.bindEnvironment 或 Meteor.wrapAsync 来创建同步代码
  • The documents are inserted unordered and may not be in the original order you added them in.文档是无序插入的,可能与您添加它们的原始顺序不同。
  • It may take 10 seconds for Meteor to see the documents 'Reactively' through a publish method if your instance is not oplog enabled.如果您的实例未启用 oplog,Meteor 可能需要 10 秒才能通过发布方法“被动地”查看文档。

Extending @Akshat's answer, this is the syntax that would work on Meteor 1.0+扩展@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)();

Here's what I use:这是我使用的:

/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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM