rubymongodbmongoidruby-2.0mongoid4

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?


Solution

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