Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add multiple documents in meteor through collection.insert()?

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.

like image 992
loomi Avatar asked Aug 24 '13 10:08

loomi


2 Answers

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.

like image 97
Tarang Avatar answered Oct 07 '22 03:10

Tarang


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

like image 23
Fabian Vogelsteller Avatar answered Oct 07 '22 02:10

Fabian Vogelsteller