Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does inserting multiple documents in a Meteor Collection work the same as pure mongodb?

Tags:

mongodb

meteor

It seems I can't do a multiple insert in Meteor the same way it is described here in the Mongodb documentation...

In my js console :

> Test.insert([{name:'hello'},{name:'hello again'}])

It returns

  "g3pq8GvWoJiWMcPkC"

And when I go

Test.find().fetch()

I get the following :

Object
0: Object
name: "hello"
__proto__: Object
1: Object
name: "hello again"
__proto__: Object
_id: "g3pq8GvWoJiWMcPkC"
__proto__: Object

It seems Meteor creates a super document encompassing the two I'm trying to insert as separate ones.

Could someone tell me what I'm doing wrong here?

like image 211
Mercutionario Avatar asked Mar 09 '13 02:03

Mercutionario


2 Answers

From the Meteor leaderboard example code, it looks like you cannot bulk insert. You can either use a loop or underscore iteration function.

Using underscore,

var names = [{name:'hello'},{name:'hello again'}]

_.each(names, function(doc) { 
  Test.insert(doc);
})
like image 124
Prashant Avatar answered Oct 09 '22 18:10

Prashant


You should always use bulk insert for these things. Meteor doesn't support this out of the box. You could use the batch insert plugin or access the node Mongodb driver to do it natively:

var items = [{name:'hello'},{name:'hello again'}],

    testCollection = new Mongo.Collection("Test"),
    bulk = testCollection.rawCollection().initializeUnorderedBulkOp();

for (var i = 0, len = items.length; i < len; i++) {
    bulk.insert(  items[i] );
}

bulk.execute();

Note that this only works on mongoDB 2.6+

like image 36
Dimitri van der Vliet Avatar answered Oct 09 '22 19:10

Dimitri van der Vliet