嗨,当我尝试继续错误插入许多它在mongoid中不起作用。
我设置了以下唯一索引
db.push_notifications.createIndex({actor_vid:1,campaign_id:1},{unique:true,partialFilterExpression:{campaign_id:{$ exists:true}}})
PushNotification.collection.insert_many([{:campaign_id =>" 1",:actor_vid => 9},{:campaign_id =>" 1",:actor_vid => 8}],:continue_on_error => true,:safe => false)
PushNotification.collection.insert_many([{:campaign_id =>" 1",:actor_vid => 9},{:campaign_id =>" 1",:actor_vid => 10}],:continue_on_error => true,:safe => false) 抛出
Mongo :: Error :: BulkWriteError:Mongo :: Error :: BulkWriteError
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongo-2.2.5/lib/mongo/bulk_write/result.rb:184:in validate!'
from /home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongo-2.2.5/lib/mongo/bulk_write/result_combiner.rb:73:in
结果'
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongo-2.2.5/lib/mongo/bulk_write.rb:65:in execute'
from /home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongo-2.2.5/lib/mongo/collection.rb:385:in
bulk_write'
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongo-2.2.5/lib/mongo/collection.rb:363:in insert_many'
from /home/deploy/.bundler/notification_service/ruby/2.2.0/gems/mongoid-5.1.3/lib/mongoid/query_cache.rb:168:in
insert_many_with_clear_cache'
来自(irb):133
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in start'
from /home/deploy/.bundler/notification_service/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in
start'
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in console'
from /home/deploy/.bundler/notification_service/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in
run_command!'
来自/home/deploy/.bundler/notification_service/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in <top (required)>'
from script/rails:6:in
要求&#39;
来自script / rails:6:在`&#39;
或 mysql插入忽略的 mongo 等价物是什么?我需要在唯一键
上绕过错误执行insert_many操作答案 0 :(得分:3)
continue_on_error 不是insert_many的选项,而是使用无序插入。通过指定 ordered:false ,插入将以无序方式发生并且它将尝试插入所有请求。包括try catch块将确保它在异常后不会中断,因此您实现了MYSQL INSERT IGNORE等效项。 如果你使用ROR,这就是你的代码应该是这样的,
开始
PushNotification.collection.insert_many([{:campaign_id =&gt;“1”,:actor_vid =&gt; 10},{:campaign_id =&gt;“1”,:actor_vid =&gt; 11},{:campaign_id = &gt;“1”,:actor_vid =&gt; 12}],{:ordered =&gt; false})
PushNotification.collection.insert_many([{:campaign_id =&gt;“1”,:actor_vid =&gt; 10},{:campaign_id =&gt;“1”,:actor_vid =&gt; 11},{:campaign_id = &gt;“1”,:actor_vid =&gt; 13}],{:ordered =&gt; false})
resque =&gt;前
提出ex.message
端
因此,在块执行后,您将插入4个新条目,并且2个Mongo :: Error :: BulkWriteError Exception。