Spring Data MongoDB-在哪里以编程方式为Mongo集合创建索引? [英] Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?

查看:763
本文介绍了Spring Data MongoDB-在哪里以编程方式为Mongo集合创建索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为集合创建索引(如此处 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.

Mongo配置中的某处?我在这里

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆