如何在ruby中处理mongodb的E11000重复键错误

时间:2013-06-05 01:51:26

标签: ruby mongodb exception-handling error-handling

在ruby中处理与mongodb相关的异常有什么好的例子吗? 在这种情况下,我有:

/home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/networking.rb:89:in `send_message_with_gle': 11000: E11000 duplicate key error index: somedb.somecoll.$_id_  dup key: { : "some_id" } (Mongo::OperationFailure)
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1108:in `block in insert_documents'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:33:in `block in instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:65:in `instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:32:in `instrument'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1106:in `insert_documents'
    from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:375:in `insert'
    from lib/tasks/getorders.rb:47:in `block in <main>'
    from lib/tasks/getorders.rb:25:in `each'
    from lib/tasks/getorders.rb:25:in `<main>'

我遇到此错误,因为我正在尝试插入一个已存在于mongodb数据库中的id的文档,我只是想知道如何处理ruby中与mongodb相关的异常。 例如,如果发生异常,那么我将更改散列的id,然后重新尝试插入它。

救援块的外观如何?

3 个答案:

答案 0 :(得分:5)

红宝石块看起来像:

begin
  # your operation
rescue Mongo::OperationFailure => e
  if e.message =~ /^11000/
    puts "Duplicate key error #{$!}"
    # do something to recover from duplicate
  else
    raise e
  end
end
# the rest of the exceptions follow ..
# if you just care about the dup error
# then ignore them
#rescue Mongo::MongoRubyError
#  #Mongo::ConnectionError, Mongo::ConnectionTimeoutError, Mongo::GridError, Mongo::InvalidSortValueError, Mongo::MongoArgumentError, Mongo::NodeWithTagsNotFound
#  puts "Ruby Error :  #{$!}"
#rescue Mongo::MongoDBError
#  # Mongo::AuthenticationError, Mongo::ConnectionFailure, Mongo::InvalidOperation, Mongo::OperationFailure
#  puts "DB Error :  #{$!}"
#rescue Mongo::OperationTimeout
#  puts "Socket operation timeout Error :  #{$!}"
#rescue Mongo::InvalidNSName
#  puts "invalid collection or database Error :  #{$!}"
#end

但是,如果您要更新已存在的记录,为什么不使用upsert

如果您要创建新记录,那么为什么不让mongod创建_id?

答案 1 :(得分:0)

也可以使用写问题。

@mongo_client.save({:doc => 'foo'}, {:w => 0}) # writes are not acknowledged

这不如救援那么好。

答案 2 :(得分:0)

如果您的ruby驱动程序是<div class="sorting_ g-green"></div> <div class="sorting_ g-pink"></div> <div class="sorting_ g-blue"></div> <div class="sorting_ grey"></div>,那么对于大多数与mongodb相关的异常,您应该使用>= 2.0.0类。以下是Mongo::Error块的外观:

rescue