Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 615
Maxim Avatar asked Nov 01 '17 13:11

Maxim


People also ask

How do I index a collection in MongoDB?

MongoDB provides a method called createIndex() that allows user to create an index. The key determines the field on the basis of which you want to create an index and 1 (or -1) determines the order in which these indexes will be arranged(ascending or descending).

How do you create an index on a field in MongoDB?

Single indexing in MongoDB is straightforward. To start, select a database that already contains collections. Once you choose a database, use the createIndex() command in the shell to create a single index.

Does MongoDB automatically create indexes?

MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value; you do not need to explicitly specify the multikey type.

Which is the method used to create index in MongoDB?

Creating an Index in MongoDB is done by using the “createIndex” method.


1 Answers

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)         );     } } 
like image 136
Dawid Naczke Avatar answered Sep 30 '22 06:09

Dawid Naczke