Maxim
Maxim

Reputation: 1152

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

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

Upvotes: 27

Views: 23561

Answers (2)

parsa ahani
parsa ahani

Reputation: 71

MongoDB supports compound indexes, where a single index structure holds references to multiple fields.

Let's see a quick example using compound indexes:

@QueryEntity
@Document
@CompoundIndexes({
    @CompoundIndex(name = "email_age", def = "{'email.id' : 1, 'age': 1}")
})
public class User {
    //
}

Upvotes: 2

Dawid Naczke
Dawid Naczke

Reputation: 1304

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

Upvotes: 44

Related Questions