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

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

4

1 回答 1

1

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

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

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

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

于 2014-03-04T09:18:22.167 回答