【问题标题】:How do I batch insert documents into MongoDB and only reject duplicates?如何将文档批量插入 MongoDB 并且只拒绝重复?
【发布时间】:2014-11-15 05:31:25
【问题描述】:

从我的 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 })

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

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

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

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

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

    【讨论】:

    • 根据this post,我好像不能同时使用mongo gem 和mongoid gem。该帖子建议改用mopedmoped可以做同样的操作吗?
    【解决方案2】:

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

      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
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多