Spring Data MongoDB-在哪里以编程方式为Mongo集合创建索引? [英] Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?
问题描述
为集合创建索引(如此处 https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/)一个人可以使用以下内容:
To create an index for a collection (as documented here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/) one can use something like the following:
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
但是我应该在程序的哪个位置放置此代码段?
But where in the program should I place this code snippet?
在相关存储库的构造函数中?我现在已经这样做了,并且可以正常工作,但是我不知何故觉得它是不好的设计.
In the relevant repository's constructor? I've did it like that now and it works, but I somehow feel like it is bad design.
Somewhere in Mongo configuration? I haven't found a suitable method to override for that here https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html
推荐答案
如果您需要以编程方式进行操作,则只需创建新的Spring的@Configuration并执行以下初始化即可:
If you need to do it in programmatic way, you can just create new Spring's @Configuration and perform such initialization:
@Configuration
@DependsOn("mongoTemplate")
public class CollectionsConfig {
@Autowired
private MongoTemplate mongoTemplate;
@PostConstruct
public void initIndexes() {
mongoTemplate.indexOps("collectionName") // collection name string or .class
.ensureIndex(
new Index().on("name", Sort.Direction.ASC)
);
}
}
这篇关于Spring Data MongoDB-在哪里以编程方式为Mongo集合创建索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!