MongoDB 唯一索引不允许覆盖 [英] MongoDB unique indexes disallow overwrite

查看:56
本文介绍了MongoDB 唯一索引不允许覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Mongo 文档中的一个字段上创建了一个 unique=true 的索引.这按预期工作 - 它通过覆盖现有条目来禁止重复.

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.

我想禁止覆盖,而是在尝试插入重复项时收到错误或异常.有没有办法做到这一点?我将如何使用 Spring Data MongoDB 执行此操作?

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?

推荐答案

通过将 WriteConcern=SAFE 添加到 MongoTemplate 配置中,我能够在违反unique=true"约束时获得异常.我处理异常并禁止覆盖.

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.

这篇关于MongoDB 唯一索引不允许覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆