使用Mongoid批量插入多个记录?

时间:2014-03-04 07:10:19

标签: ruby mongodb mongoid ruby-2.0 mongoid4

我正在阅读this Stackoverflow answer,了解如何在一个查询中在Mongoid中插入多个文档。从我读到的答案:

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

我需要一个例子来了解它是如何工作的。假设我们有文章类:

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

如何创建它们,同时确保验证捕获的2个remote_id是相同的?

1 个答案:

答案 0 :(得分:0)

如果为remote_id字段添加唯一索引,MongoDB将关注此字段的唯一性

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

不要忘记运行create_indexes:rake db:mongoid:create_indexes

之后,您可以自由使用Article.collection.insert(batch)