I like to add multiple documents at once in a collection in meteor.
MongoDB supports this from 2.2:
db.collection.insert([{docNumber: 1},{docNumber: 2}])
Is it possible to achieve this behaviour also in Meteor? Something like:
myCollection.insert([{docNumber: 1},{docNumber: 2}])
Currently this will be added as one document. I can unfortunately not live with an iterator because the use case is loading more than 100'000 documents. This is to slow with single inserts.
Batch insertion isn't yet possible with Meteor. Though you could make an iterator to help you insert documents in an array
var docs = [{docNumber: 1},{docNumber: 2}];
_.each(docs, function(doc) {
myCollection.insert(doc);
});
It might be possible to do it on the server end, albeit with a bit of modifications to expose a bulk insertion method. The problem with this though is this code wouldn't work on the client end.
I wrote a simple script to bulk insert. It works only on the client side by inserting documents to the collection without reactivity. only the last item will call the reactive computations.
insertBulk = function(collection, documents){
if(collection) {
return _.compact(_.map(documents, function(item){
if(_.isObject(item)) {
var _id = collection._makeNewID();
// insert with reactivity only on the last item
if(_.last(documents) === item)
_id = collection.insert(item);
// insert without reactivity
else {
item._id = _id;
collection._collection._docs._map[_id] = item;
}
return _id;
}
}));
}
}
You can find an example script including removebulk() function here: https://gist.github.com/frozeman/88a3e47679dd74242cab
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With