title: Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?
body: <p>To create an index for a collection (as documented here <a href="https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/" rel="noreferrer">https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/</a>) one can use something like the following:</p>
  
  <pre><code>mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
  </code></pre>
  
  <p>But where in the program should I place this code snippet? </p>
  
  <p>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.</p>
  
  <p>Somewhere in Mongo configuration? I haven't found a suitable method to override for that here <a href="https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html" rel="noreferrer">https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html</a></p>