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