问题
I have a unique index setup, with drop_dup: true
index({ key1: 1, key2: 1 }, { unique: true, drop_dups: true })
When inserting multiple records, I would like the non-duplicates to succeed, similar to MySQL's
INSERT IGNORE INTO table ...
.. or even INSERT INTO table ... ON DUPLICATE KEY UPDATE
So if I have a record:
Model.collection.insert({'key1'=>'not-unique', 'key2'=>'boo'})
It seems that the following call doesn't do anything.
Model.collection.insert(
{'key1'=>'not-unique', 'key2'=>'boo'},
{'key1'=>'im-unique', 'key2'=>'me-too'}
)
Is there a way to at least insert {'key1'=>'im-unique', 'key2'=>'me-too'}
on the 2nd call?
Thanks!
回答1:
It appears that you are looking for insert batch with continue_on_error and not single document update/upsert of which I think you are already informed.
http://api.mongodb.org/ruby/current/Mongo/Collection.html#insert-instance_method
With the 10gen driver, an equivalent of your example with a User model would be:
Gemfile
gem 'mongo'
gem 'bson_ext'
test/unit/user_test.rb (excerpt)
col = Mongo::Connection.new['sandbox_test']['users']
col.insert({'key1'=>'not-unique', 'key2'=>'boo'})
assert_equal(1, User.count)
col.insert([{'key1'=>'not-unique', 'key2'=>'boo'},{'key1'=>'im-unique', 'key2'=>'me-too'}], :continue_on_error => true)
assert_equal(2, User.count)
The above works in a simple unit test.
Mongoid 3 uses the Moped driver instead of the 10gen driver. In the 1.1.6 gem that you are using, moped does not support options / flags, but Durran added flags to the insert method circa July 28 in github.
https://github.com/mongoid/moped/commit/2c7d6cded23f64f436fd9e992ddc98bbb7bbdaae
https://github.com/mongoid/moped/commit/f8157b43ef0e13da85dbfcb7a6dbebfa1fc8735c
As of mongoid 3.0.3 with moped 1.2.0, the following insert batch with continue_on_error works.
Model.collection.insert([{'key1'=>'not-unique', 'key2'=>'boo'},{'key1'=>'im-unique', 'key2'=>'me-too'}], [:continue_on_error])
Note that the primary parameter to the insert method for batch insert is an Array object enclosed in square brackets - the square brackets are missing from your post.
Hope that this helps.
来源:https://stackoverflow.com/questions/11752991/mongoid-ignores-collection-insert-if-at-least-one-duplicate-exists