首页 > 解决方案 > 如何在 Spring 中使用 MongoDB 强制执行唯一字段

问题描述

我有一个 pojo,其中包含两个需要唯一的字段,即 id 和电子邮件。所以我@Indexed(unique = true)像这样将注释添加到必要的字段中

public class User {
    @Id
    @Indexed(unique = true)
    private String id;
    @Indexed(unique = true)
    private String email;
    private int money;

然后我对其进行了测试,但没有强制执行。所以我搜索了一下,我在这里找到了以前的答案 - Spring Data:MongoDB 文档中的唯一字段,随后删除了集合,添加spring.data.mongodb.auto-index-creation=true到我的 application.properties 文件并再次尝试。

但是,仍然没有强制执行唯一字段!我看到有另一个答案在使用ensureIndex(),但它也有一个很好的评论,从来没有回答过-Why do we need to use the annotation if all the work is done on mongoTemplate?

因此,由于问题已经足够老了,显然唯一可行的答案已被贬低(新方法是 using createIndex()),我认为是时候推出新版本了。是否可以要求 mongo 集合中的列在 Spring Boot 中是唯一的?

标签: javamongodbspring-bootunique-index

解决方案


推荐阅读