0

我有一个独特的索引设置,drop_dup: true

index({ key1: 1, key2: 1 }, { unique: true, drop_dups: true })

插入多条记录时,我希望不重复成功,类似于 MySQL 的

INSERT IGNORE INTO table ...

.. 甚至INSERT INTO table ... ON DUPLICATE KEY UPDATE

所以如果我有记录:

Model.collection.insert({'key1'=>'not-unique', 'key2'=>'boo'})

似乎以下调用没有做任何事情。

Model.collection.insert(

{'key1'=>'not-unique', 'key2'=>'boo'},

{'key1'=>'im-unique', 'key2'=>'me-too'}

)

有没有办法至少{'key1'=>'im-unique', 'key2'=>'me-too'}在第二次通话中插入?

谢谢!

4

1 回答 1

0

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.

于 2012-08-02T13:37:24.057 回答