我正在使用Spring Data MongoDB开发应用程序。我想在我的一个模型上创建一个复合索引。我在顶部添加了@CompoundIndex注释,如下所示:
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 { }但是,未创建索引。我还尝试直接在类上面放置 @CompoundIndex 。该集合仍然缺少索引。当像这样创建时,相同的索引定义工作正常:
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?
推荐答案在这种情况下,我宁愿选择mongodb createIndex 方法,因为它确保已创建索引,即使您在应用程序模型中创建它们(在这种情况下为Spring启动),最好还是进行双重检查并手动创建它们 docs.mongodb/v3.2/reference/method/db.collection.createIndex/
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 docs.mongodb/v3.2/reference/method/db.collection.createIndex/
更多推荐
@CompoundIndex在Spring Data MongoDB中不起作用
发布评论