【问题标题】:MongoDB unique index not created In spring bootMongoDB 唯一索引未在 Spring Boot 中创建
【发布时间】:2020-09-13 16:49:05
【问题描述】:

在 Spring boot + MongoDB 应用程序中,我正在尝试为电子邮件字段创建唯一索引。

@Document
public class User {

    @Id
    private String id;

    @Indexed(unique = true)
    private String email;

}
public interface UserRepository extends MongoRepository<User, String>

但我仍然可以使用同一电子邮件插入两个用户对象,所以

userRepository.save(new User("my@email.com"))
userRepository.save(new User("my@email.com"))

在用户集合中创建两个条目。

我做错了什么?

我知道Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?,但我正在寻找“仅注释”的解决方案。

【问题讨论】:

    标签: java spring mongodb spring-boot


    【解决方案1】:

    我解决了这个问题之后的问题: Spring Data: Unique field in MongoDB document

    所以你应该在 MongoTemplate + @indexed 注释中创建索引。

    【讨论】:

      【解决方案2】:

      我引用documentation

      Spring Data MongoDB 可以自动为带有 @Document 注释的实体类型创建索引。从 3.0 版开始,必须明确启用索引创建,以防止对集合生命周期和性能造成不良影响。

      您是否启用了自动索引创建?因为如果您不这样做,那很可能是您的唯一约束不被遵守的原因。您可以通过连接到 MongoDB 实例并运行 db.user.getIndexes() 来验证不存在任何索引。这将打印您的用户集合的索引。

      使用 Spring Boot,您可以在 application.yml 中使用以下配置启用自动索引创建:

      spring:
        data:
          mongodb:
            auto-index-creation: true
      

      或者如果您更喜欢属性:

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

      【讨论】:

        【解决方案3】:

        检查 - https://docs.mongodb.com/manual/core/index-unique/

        它指出 - 如果集合已经包含违反索引唯一约束的数据,MongoDB 无法在指定的索引字段上创建唯一索引。

        因此,如果您的收藏集很少有文档已经具有相同的电子邮件值,那么如果您尝试在电子邮件字段上创建索引,它可能无法正常工作。检查您是否有此类文件。

        【讨论】:

        • 谢谢,但集合是空的。
        • @cnmuc 尝试清除整个数据库,然后重试。它对我有用
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 2014-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多