我正在阅读这个 Stackoverflow 答案,了解如何在一个查询中在 Mongoid 中插入多个文档。从我读到的答案中:
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?
如果您为
remote_id
字段添加唯一索引,MongoDB 将照顾该字段的唯一性
index({ remote_id: 1 }, { unique: true })
不要忘记运行create_indexes:
rake db:mongoid:create_indexes
之后就可以自由使用了
Article.collection.insert(batch)
。
正如 Zakwan 提到的,创建一个唯一索引。
从 Mongoid 8 和 Mongo 2.19 开始,使用
insert_many
Article.collection.insert_many batch
https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/