0

I'm using a Meteor.Method and trying to insert multiple documents as show in online documents

I'm using this pattern to produce an array of documents to insert.

  var arr = [];

  for (i=0;i<10;i++){
    doc = {}
    doc["A"] = i;
    doc["B"] = i*18;
    arr.push(doc)
  }

  bulks.insert(arr)

instead of inserting multiple documents, it embeds each document in my arr into a single new document:

{
        "_id" : "YqfTbSmrGEcTAhFhj",
        "0" : {"A" : 0, "B" : 0 },
        "1" : {"A" : 1,"B" : 18},
        "2" : {"A" : 2,"B" : 36},
        "3" : {"A" : 3,"B" : 54},
        {...},
        "9" : {"A" : 9,"B" : 162}
}

How can I construct the array to ensure that the documents are inserted individualy?

e.g.

{ "_id" : "YqfTbSmrGEcTAhFhj", "A" : 0, "B" : 0 }
{ "_id" : "mrGEcTAhFhjYqfTbS", "A" : 1, "B" : 18 }
{ "_id" : "hjYqfTmrGEcTAhFbS", "A" : 2, "B" : 36 }
{...}
{ "_id" : "hjYqfTmrGEcTAhFbS", "A" : 9, "B" : 182}

[added info] I have been successfully able to do this in the shell, but not in Meteor - so it is possible a limitation of the driver.

Is it possible to do this with Meteor?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
garrilla
  • 539
  • 5
  • 15
  • I tried you code in mongodb 2.4.8 and its working fine and inserting separate docs, which version of mongodb you are using? – Saheed Hussain Jun 10 '14 at 10:51
  • I'm guessing there is a discrepancy between what you've posted here and what you're actually running. bulks.insert(arr) is not valid syntax for the shell, it should be db.bulks.insert(arr). Are you doing this in the mongo shell or with a driver? Can you try printing arr before you insert? Just type arr in the shell. – helmy Jun 10 '14 at 11:23
  • I'm just adding this to the question as I now realise it is driver issue... I'm using Meteor – garrilla Jun 10 '14 at 11:28
  • Why not insert them where you use `arr.push`? – Tarang Jun 10 '14 at 11:55
  • @Akshat takes too long to insert each individually... – garrilla Jun 10 '14 at 12:23

2 Answers2

0

Meteor collections are not 100% direct translations of Mongo collections, they're wrapped in a separate layer. Therefore, you cannot directly use Mongo methods on them. The insert you used was a Meteor collection insert. Per the documentation, it only allows you to insert a single document at a time.

Hubert OG
  • 19,314
  • 7
  • 45
  • 73
0

According to this Github discussion/closed issue of April 22 2014 it is not possible to bulk insert and it is cisdiered for the future but, according to the roadmap not scheduled.

The answer to Bulk mongodb insert in Meteor or Node shows how it can be achieved with a work around in node.

Community
  • 1
  • 1
garrilla
  • 539
  • 5
  • 15