如何在Java中使用Spring Data以编程方式创建MongoDB组合索引?
使用MongoTemplate,可以像这样创建索引:
mongoTemplate.indexOps(“collectionName”). ensureIndex(new Index()。 on(“fieldName”,Sort.Direction.DESC))
。
是否有一种方法来创建复合键?
我看到有一个名为CompoundIndexDefinition的类似乎可以做到这一点,但我无法让它工作。
如何在Java中使用Spring Data以编程方式创建MongoDB组合索引?
使用MongoTemplate,可以像这样创建索引:
mongoTemplate.indexOps(“collectionName”). ensureIndex(new Index()。 on(“fieldName”,Sort.Direction.DESC))
。
是否有一种方法来创建复合键?
我看到有一个名为CompoundIndexDefinition的类似乎可以做到这一点,但我无法让它工作。
您可以按以下方式在Java中以编程方式使用Spring Data在任何集合上创建复合索引:
// Compound indexes on the fields: fieldOne & fieldTwo
// db.groups.createIndex({fieldOne:1, fieldTwo:1})
IndexDefinition index =
new CompoundIndexDefinition(new Document().append("fieldOne", 1).append("fieldTwo", 1));
mongoTemplate.indexOps(CollectionName.class).ensureIndex(index);
db.groups.createIndex({fieldOne:1, fieldTwo:1})
mongoTemplate.indexOps(CollectionName.class)
.ensureIndex(new Index().on("fieldOne", Sort.Direction.DESC)
.on("fieldTwo", Sort.Direction.ASC));
mongoOperations.indexOps(CollectionName.class)
.ensureIndex(new Index().on("fieldOne", Sort.Direction.DESC)
.on("fieldTwo", Sort.Direction.ASC));
我认为这是更合适的方法。
@CompoundIndexes({
@CompoundIndex(name = "customIndex", def = "{'fieldOne' : 1, 'fieldTwo': 1}")
})
public class Entity {}
spring.data.mongodb.auto-index-creation=true
来启用它。 - Mirko Perillo