Techioz Blog

Mongoidで複数のレコードをバッチ挿入しますか?

概要

1 つのクエリで Mongoid に複数のドキュメントを挿入する方法について、この Stackoverflow の回答を読んでいます。私が読んだ答えから:

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

これがどのように機能するかを理解するには例が必要です。 Article クラスがあるとします。

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

そして、私は例えば。記事の配列を作成します。

[ {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"} ]

これらを作成し、同時に検証で同じremote_idが2つあることを確認するにはどうすればよいですか?

解決策

Remote_id フィールドに一意のインデックスを追加すると、MongoDB はこのフィールドの一意性を考慮します。

インデックス({リモートID: 1 }, {一意: true })

create_indexes: rake db:mongoid:create_indexes を実行することを忘れないでください。

その後は、Article.collection.insert(batch) を自由に使用できます。