1

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?

Community
  • 1
  • 1
Cjoerg
  • 1,271
  • 3
  • 21
  • 63

1 Answers1

1

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).

Zakwan
  • 1,072
  • 2
  • 11
  • 22
  • Thanks for this answer. But where should `index({ remote_id: 1 }, { unique: true })` be put in. Is it into the model? – Cjoerg Mar 04 '14 at 11:16
  • yes, see the doc for more details http://mongoid.org/en/mongoid/docs/indexing.html – Zakwan Mar 04 '14 at 11:30
  • Any idea how you create the indexes on the server. Locally, you can simply create the index from the terminal at your terminal location. But on the server it seems that I can't do it from `~/applications/myapp/current`. – Cjoerg Apr 04 '14 at 05:55