如何将文档批量插入MongoDB并仅拒绝重复?

时间:2014-11-15 05:31:26

标签: ruby-on-rails mongodb mongoid

从我的Ruby on Rails应用程序中,我需要将Customer文档插入 MongoDB 。出于性能原因,我需要批量插入它们:

Customer.collection.insert([{mail_address: "hello_1@hello_1.com"}, {mail_address: "hello_2@hello_2.com"}])

我有一个索引来强制mail_address属性的唯一性:

index({ mail_address: 1 },  { background: true, unique: true })

但这意味着如果一个失败,整个批次都会失败。

如何批量插入文档,只会失败/拒绝重复的文档?

2 个答案:

答案 0 :(得分:0)

如果您使用Unordered Bulk Write Operation,将尝试整个批次并返回错误报告。

这是直接使用Mongo Ruby Driver。我不认为Mongoid直接支持这个api。 This thread描述了使用Mongoid的解决方案。

答案 1 :(得分:0)

我正在批量添加记录,使用唯一索引,即使操作失败,我仍然会观察到正在创建的新记录(即它仅在重复时失败,而不是整个批量操作)。

  batch = []
    chatters.each do |chatter|
      today = Time.now.to_date
      batch.push({ :influencer_name_downcase => channel_name, :name => chatter, :date_seen => today })
    end

    begin
      a = Kuv.collection.insert_many( batch )
    rescue Mongo::Error::BulkWriteError => e
      ;
    end