2014-03-04 125 views
0

我正在通过this Stackoverflow answer阅读关于如何在一个查询中插入Mongoid中的多个文档。从我读的答案:用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的是一样的吗?

回答

0

如果添加了独特的索引为remote_id场,MongoDB的会照顾这一领域的独特性

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

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

之后,你是免费使用Article.collection.insert(batch)

+0

感谢您的回答。但是应该在哪里放入index({remote_id:1},{unique:true})。它是否在模型中? – ChristofferJoergensen

+0

是的,请参阅文档以获取更多详细信息http://mongoid.org/en/mongoid/docs/indexing.html – Zakwan

+0

任何想法如何在服务器上创建索引。在本地,您可以简单地从终端位置的终端创建索引。但在服务器上,似乎我无法从'〜/ applications/myapp/current'中执行。 – ChristofferJoergensen