英文:
How to create an index programmatically for a dynamic Mongo collection? ( Java Spring Data MongoDB )
问题
这里是你的翻译内容:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
private ObjectId _id;
private String log;
private String key;
}
正如你所见,我的集合名称是根据日期动态生成的,例如 2020-10-05
。
我想在 "key" 字段上创建一个唯一索引。怎么做?
当集合名称固定时,我可以在 MongoDB 配置类中简单地执行以下操作:
mongoTemplate.indexOps("{collection name}").ensureIndex(indexDefinition.unique());
但由于集合是动态的,我需要一种触发 PostConstruct
的方式,每次创建新集合时我都可以在其中创建索引。
英文:
I need help with this, here is my document class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
private ObjectId _id;
private String log;
private String key;
}
As you can see my collection name is dynamic depending on date, e.g. 2020-10-05
.
I want to create a unique index on the key. HOW?
When the collection name is fixed I can simply do the following in the mongo Configuration class:
mongoTemplate.indexOps("{collection name}").ensureIndex(indexDefinition.unique());
but since the collection is dynamic, I need a way to trigger a PostConstruct
for every time a new collection is created so that I can create the index.
答案1
得分: 0
答案就是使用注解
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
//对于复合索引:
@CompoundIndexes({
@CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
})
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
private ObjectId _id;
private String log;
//对于一个字段的唯一索引:
// @Indexed(unique = true)
private String key;
private String app;
}
英文:
The answer is simply using annotations
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
//For Compound index:
@CompoundIndexes({
@CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
})
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
private ObjectId _id;
private String log;
//For a unique index on one field:
// @Indexed(unique = true)
private String key;
private String app;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论