Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?

喜欢而已 提交于 2019-12-10 12:47:09

问题


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


回答1:


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)
        );
    }
}


来源:https://stackoverflow.com/questions/47055743/spring-data-mongodb-where-to-create-an-index-programmatically-for-a-mongo-coll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!