简体   繁体   中英

Bulk create in Meteor

I need to create 2000 documents at once in Meteor. I know I can use

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

but I hope there is a bulk create function in Meteor. How can I insert these 2000 rows in the fastest way possible?

Meteor doesn't natively support this. However, it does give you access to the node Mongodb driver which can natively do a bulk insert.

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:

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
  • 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.

Extending @Akshat's answer, this is the syntax that would work on 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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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