MongoDB unique indexes disallow overwrite

2019-05-16 19:47发布

I have created an index with unique=true on one of the fields in my Mongo document. This works as expected - it disallows duplicates by overwriting the existing entry.

I would like to disallow overwrites, and instead get an error or exception when an attempt is made to insert a duplicate. Is there any way to do this? How would I do this with Spring Data MongoDB?

2条回答
乱世女痞
2楼-- · 2019-05-16 20:28

The indexed annotation has a parameter dropDups=true which would give you what you want.

Indexed (unique=true, dropDups=true)

http://static.springsource.org/spring-data/data-mongodb/docs/1.1.0.RELEASE/api/org/springframework/data/mongodb/core/index/Indexed.html

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-05-16 20:53

By adding WriteConcern=SAFE to the MongoTemplate configuration, I was able to get exceptions when the "unique=true" constraint is violated. I handle the exception and disallow overwrites.

查看更多
登录 后发表回答