Spring Data: MongoDB文档中的唯一字段

20

假设我有以下数据库实体:

@Document(collection = "users")
public class User {
    
    @Id
    private String id;

    private String firstname;

    private String lastname;

    private String email; 

}

如何强制使email字段唯一?这意味着当应用程序尝试保存实体时,MongoDB应该检查是否已经存在此电子邮件地址的用户记录。


6
@Indexed(unique = true) - pDer666
3
那么它只能与@Indexed一起使用吗? - StSch
我发现了这个stackoverflow的问题/答案,对我的帮助很大:https://dev59.com/8FIG5IYBdhLWcg3w8WYC#62217147(这里没有任何答案帮助我;我正在运行Springboot 3.0.2,Mongo) - Dirk Schumacher
6个回答

22

Mongodb需要创建并索引一个字段,以便知道该字段是否唯一。

@Indexed(unique=true)
private String email;

2
我尝试过这个,但Mongo驱动程序没有进行任何强制操作来使其唯一。 - David
@David:你在Mongo的那一端创建了索引吗? - Vishnu Dahatonde

10

这对我有效,但是您必须删除您的数据库并重新运行您的应用程序。

 spring.data.mongodb.auto-index-creation=true

@Moumen- 如何在不刪除數據庫的情況下實現? - Praveen Kumar Verma

8

首先,在您的模型字段上使用以下所示的Indexed注释:

@Indexed(unique = true)
private String email;

此外,您应该通过编程方式定义您的索引。在定义您的MongoTemplate时,应使用以下代码。
mongoTemplate.indexOps("YOUR_COLLECTION_NAME").ensureIndex(new Index("YOUR_FEILD_OF_COLLECTION", Direction.ASC).unique());

对于您的情况,您应该使用:

mongoTemplate.indexOps("users").ensureIndex(new Index("email", Direction.ASC).unique());

14
如果所有工作都在 mongoTemplate 上完成,为什么我们还需要使用注解? - Yves Calaci

6

从Spring Data MongoDB 3.0开始,默认关闭自动索引创建。所以,除了使用@Indexed之外,您还需要配置默认的索引选项。您需要在application.properties文件中设置spring.data.mongodb.auto-index-creation=true,然后@Indexed就可以像魔法一样工作了!


1
您可以尝试以下解决方案,它对我有用。
注意:请在尝试以下解决方案之前删除您的数据库。
解决方案-1
@Indexed(unique = true, background = true)
private String emailId;

解决方案 - 2

在你的application.properties文件中添加spring.data.mongodb.auto-index-creation=true

或者

在你的yaml文件中添加spring.data.mongodb.auto-index-creation:true


0

如果有人有自定义的Mongo配置 -> spring.data.mongodb.auto-index-creation:true 不起作用。相反,尝试将以下内容添加到您的MongoConfig中:

       @Override
       public boolean autoIndexCreation() {
       return true;
       }

它为我解决了这个问题...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接