MongoDB unique indexes disallow overwrite

一笑奈何 提交于 2020-01-02 08:34:13

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/14033272/mongodb-unique-indexes-disallow-overwrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!