3

As explained here, it's fairly easy to batch insert an array of new documents into a MongoDB collection:

batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
Article.collection.insert(batch)

What I don't find easy though is how to retrieve the list of newly created ids. Is it possible to code something like:

batch = [{:name => "mongodb"}, {:name => "mongoid"}]
result = Article.collection.insert(batch)

result[:ids] # not real code

Thanks in advance!

Community
  • 1
  • 1
lucke84
  • 4,516
  • 3
  • 37
  • 58
  • 1
    @muistooshort Nope. I'm inserting up to millions of items (in batches of 5k) and I can't afford querying for them after each insert. – lucke84 Jan 09 '15 at 09:40
  • I'm not inserting them explicitly, but it seems like mongoid prefills those in the `_id` field when you `create` an object (not like in the example); so if you collect them before the actual bulk insert and this one is successful, you can say you've got them. I'll test the thing and write an answer to this question. – lucke84 Jan 12 '15 at 21:26
  • did you test, i want to batch insert as well... i have parent and child objects of parent, i want save with association in batch save – user1735921 Jul 25 '16 at 07:32

1 Answers1

0

You can now access this data with inserted_ids https://www.mongodb.com/docs/ruby-driver/master/api/Mongo/BulkWrite/Result.html so for your example it would be

batch = [{:name => "mongodb"}, {:name => "mongoid"}]
result = Article.collection.insert_many(batch)

result.inserted_ids