Cjoerg
Cjoerg

Reputation: 1325

Batch insert multiple records with Mongoid?

I am reading through this Stackoverflow answer about how to insert multiple documents in Mongoid in one query. From the answer I read:

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

I need an example to understand how this works. Say we have the Article class:

class Article
  include Mongoid::Document
  include Mongoid::Timestamps

  field :subject,   type: String
  field :body,      type: String
  field :remote_id, type: String

  validates_uniqueness_of :remote_id

  belongs_to :news_paper,   :inverse_of => :articles
end

And the I e.g. create an array of articles:

[ {subject: "Mongoid rocks", body: "It really does", remote_id: "1234", news_paper_id: "abc"},
{subject: "Ruby rocks", body: "It really does", remote_id: "1234", news_paper_id: "abc"},
{subject: "Rails rocks", body: "It really does", remote_id: "5678", news_paper_id: "abc"} ]

How do I create them, and at the same time make sure the validation catches that I have 2 remote_id's that are the same?

Upvotes: 1

Views: 1256

Answers (2)

B Seven
B Seven

Reputation: 45941

As Zakwan mentioned, create a unique index.

As of Mongoid 8 and Mongo 2.19, use insert_many

Article.collection.insert_many batch

https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/

Upvotes: 0

Zakwan
Zakwan

Reputation: 1072

If you add a unique indexing for remote_id field, MongoDB will take care the uniqueness of this field

index({ remote_id: 1 }, { unique: true })

Don't forget to run create_indexes: rake db:mongoid:create_indexes

After that, you are free to use Article.collection.insert(batch).

Upvotes: 1

Related Questions