16

I am working on an application using Spring Data MongoDB. I would like to create a compound index on one of my models. I have added a @CompoundIndex annotation at the top like so:

@Document
@CompoundIndexes({
    @CompoundIndex(name = "name_", def = "{ 'tenantId': 1, 'name': 1 }", unique = true)
})
public class MyModel {

}

However, the index is not created. I have also tried to directly place the @CompoundIndex above the class. The collection is still missing the index. The same index definition is working fine when created like so:

mongoTemplate.indexOps(MyModel.class).ensureIndex(new Index().named("name_").on("tenantId", Direction.ASC).on("name", Direction.ASC).unique());

I'd prefer to use the annotation-based definition of the index. Any ideas why this is not working?

Fynn
  • 4,753
  • 3
  • 32
  • 69
  • Have you tried http://pastebin.com/PynPCgRY ? – chridam Jun 11 '15 at 07:42
  • I did now and it does not change the behavior... – Fynn Jun 11 '15 at 08:03
  • Hi! May I ask you to post the whole application ? It would be great if you're able to provide the Spring context at least. – danidemi Nov 17 '15 at 22:35
  • I had the same problem, index was not created using the annotation, but it was created using ensureIndex explicitly. The i realised i was missing the Document annotaton. Now the index is created with the CompundIndex annotation. – Sbiera Bogdan Jun 21 '16 at 10:38
  • I'm having the same problem right now in Spring Boot 1.4 with Spring Data Mongo 1.9.2 and the Mongo 3.2 java driver. – Mike Twain Sep 08 '16 at 19:28
  • Have you find an answer? my problem is http://stackoverflow.com/questions/39847601/spring-data-mongodb-unable-to-find-index-via-mongo – dmitryvim Oct 04 '16 at 08:32

3 Answers3

16

You need to add the following to application.properties:

spring.data.mongodb.auto-index-creation=true

or in application.yml:

spring:
  data:
    mongodb:
      auto-index-creation: true
Ja'afar Naddaf
  • 357
  • 4
  • 13
  • 6
    4 years later and finding this bit of documentation is still difficult. but it fixed my problem - thank you! – Jake Stout Sep 10 '20 at 13:03
1

Couple years later, I faced the same issue. If none of above answers work for you (just like for me), try overriding autoIndexCreation() in MongoConfig class.

@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
  @Override
  protected boolean autoIndexCreation() {
    return true;
  }
}
Wiktor
  • 71
  • 1
  • 9
0

In this case I would rather go with mongodb createIndex method as it ensures indexes have been created, even if you created them in your app models (Spring boot in this case) it's always better to do a double check and create them manually https://docs.mongodb.com/v3.2/reference/method/db.collection.createIndex/

Waheed
  • 608
  • 1
  • 5
  • 20