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

后端 未结 1 1002
鱼传尺愫
鱼传尺愫 2021-01-03 22:57

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:

相关标签:
1条回答
  • 2021-01-03 23:14

    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)
            );
        }
    }
    
    0 讨论(0)
提交回复
热议问题