@CompoundIndex在Spring Data MongoDB中不起作用

我正在使用Spring Data MongoDB开发应用程序。 我想在我的一个模型上创建一个复合索引。 我在顶部添加了@CompoundIndex注释,如下所示:

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

但是,不会创建索引。 我也尝试将@CompoundIndex直接放在类上面。 该集合仍然缺少索引。 创建时,相同的索引定义正常工作:

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

我更喜欢使用索引的基于注释的定义。 任何想法为什么这不起作用?

在这种情况下,我宁愿使用mongodb createIndex方法,因为它确保已创建索引,即使您在应用程序模型中创建它们(在这种情况下为Spring启动),最好还是进行双重检查并手动创建它们:https:/ /docs.mongodb.com/v3.2/reference/method/db.collection.createIndex/

Interesting Posts