Java – @ compoundindex does not work in spring data mongodb
I am using spring data mongodb to process applications I want to create a composite index on one of my models I added the @ compoundindex comment at the top, as follows:
@Document @CompoundIndexes({ @CompoundIndex(name = "name_",def = "{ 'tenantId': 1,'name': 1 }",unique = true) }) public class MyModel { }
However, the index is not created I also try to put @ compoundindex directly on the class The collection is still missing an index When created, the same index definition works properly:
mongoTemplate.indexOps(MyModel.class).ensureIndex(new Index().named("name_").on("tenantId",Direction.ASC).on("name",Direction.ASC).unique());
I prefer to use annotation - based definitions of indexes Any idea why this doesn't work?
Solution
In this case, I prefer to use the mongodb createindex method because it ensures that indexes are created, and even if you create them in the application model (in this case, spring starts), it's best to double check and create them manually https://docs.mongodb.com/v3.2/reference/method/db.collection.createIndex/