Spring Data - MongoDB indexing DBRef Spring Data - MongoDB indexing DBRef mongodb mongodb

Spring Data - MongoDB indexing DBRef


You can create the index with the mongo shell, but if you want to do it through code and since you are using spring-data-mongodb, use this:

mongoTemplate.indexOps(B.class).ensureIndex(new Index().on("a", Order.ASCENDING));

You can also specify the name of the collection if the name of your class doesn't match it:

mongoTemplate.indexOps("b").ensureIndex(new Index().on("a", Order.ASCENDING));


I think this will work:@CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")@Document(collection = "b")public class B {...}

If not, you can call mongoTemplate.indexOps("b").ensureIndex(...) in a method annotated with @PostConstruct or so


I had the same problem, for me the orid's solution worked but I had to wrap the @CompoundIndex inside a @CompoundIndexes otherwise it didn't work (I'm using Spring Roo).

@CompoundIndexes({    @CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")})@Document(collection = "b")public class B {...}