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

有没有在ruby中处理mongodb相关exception的好例子? 在这种情况下,我有:

/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 ' from lib/tasks/getorders.rb:25:in `each' from lib/tasks/getorders.rb:25:in `' 

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

救援区怎么样?

ruby块看起来像:

 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?

也可以使用写问题。

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

但这并不像救​​援那么好。

如果您的ruby驱动程序>= 2.0.0 ,则应该对大多数与mongodb相关的exception使用Mongo::Error类。 以下是您的rescue区应如何:

 begin # Document insert code rescue Mongo::Error => e if e.message.include? 'E11000' # Change the id of the hash & re-try to insert it end end