要为集合创建索引(如https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/所述),可以使用以下内容:
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
Run Code Online (Sandbox Code Playgroud)
但是我应该在程序的哪个位置放置此代码段?
在相关的存储库的构造函数中?我现在已经这样做了它并且它可以工作,但我不知何故觉得这是糟糕的设计.
在Mongo配置的某个地方?我还没有找到一个合适的方法来覆盖这里https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html
我有以下课程作为我的文档。
@Data
@Builder
@Document(collection = "test")
public class TestData {
@Id
private String id;
private String name;
@Indexed(unique = true)
private String hash;
}
Run Code Online (Sandbox Code Playgroud)
即使我使用启用了唯一性的索引,我也可以将重复文档插入到集合中。但如果我在 mongo shell 中生成索引,那么它就可以工作。
有什么方法可以仅通过代码指定唯一索引吗?
我正在使用Spring Data MongoDB处理应用程序.我想在我的一个模型上创建一个复合索引.我在顶部添加了@CompoundIndex注释,如下所示:
@Document
@CompoundIndexes({
@CompoundIndex(name = "name_", def = "{ 'tenantId': 1, 'name': 1 }", unique = true)
})
public class MyModel {
}
Run Code Online (Sandbox Code Playgroud)
但是,不会创建索引.我也试过直接放置@CompoundIndex上面的类.该集合仍然缺少索引.创建时,相同的索引定义正常工作:
mongoTemplate.indexOps(MyModel.class).ensureIndex(new Index().named("name_").on("tenantId", Direction.ASC).on("name", Direction.ASC).unique());
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用索引的基于注释的定义.任何想法为什么这不起作用?
我知道有类似的问题,例如:Spring boot / mongo wont create index with the index comment
\nGithub 中的问题还包括“spring.data.mongodb.auto-index-creation=true”无法正常工作
\n我还尝试过这个 Baeldung 指南:Spring Data MongoDB \xe2\x80\x93 Indexes, Annotations and Converters
\n所以问题是我正在尝试使用 @Indexed 注释向现有集合添加索引,如下所示:
\n@CreatedDate\n@Indexed(name="timestamp_index", expireAfterSeconds=100))\nprivate Date timestamp;\nRun Code Online (Sandbox Code Playgroud)\n该字段是在将元素插入数据库时自动创建的时间戳。
\n该类也有@Document标签。
那么,我尝试了什么?
\nspring.data.mongodb.auto-index-creation: true根据其他答案,我做的第一件事就是以这种方式添加:
@CreatedDate\n@Indexed(name="timestamp_index", expireAfterSeconds=100))\nprivate Date timestamp;\nRun Code Online (Sandbox Code Playgroud)\n这不起作用......但我也读到问题可能出在我上课时AbstractMongoClientConfiguration。
目前该项目没有该类,但存在MongoConfiguration带有该@Configuration标签的类。我不知道这是否会干扰或其他什么。
类是这样的:
\nspring:\n data:\n mongodb:\n uri: ${env.mongo-database.url}\n auto-index-creation: true\nRun Code Online (Sandbox Code Playgroud)\n这个类创建一个@Bean命名的mongodb所以我尝试在这里手动添加自动索引为 …