如何在Spring或Spring Boot中以编程方式在Spring Mongo数据中创建复合索引?

mih*_*hal 5 spring mongodb spring-data-mongodb

如何在 Java 中以编程方式使用 Spring Data 创建 MongoDB 复合索引?

使用 MongoTemplate 我可以创建这样的索引:

mongoTemplate.indexOps("collectionName").ensureIndex(new Index().on("fieldName", Sort.Direction.DESC)

有没有办法创建复合键?

我看到有一个类CompoundIndexDefinition,从它的名字来看,它似乎是这样做的,但我无法让它工作。

kri*_*sad 9

您可以在 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);
Run Code Online (Sandbox Code Playgroud)

上面的示例将创建与 mongo shell 上相同的索引:

db.groups.createIndex({fieldOne:1, fieldTwo:1})
Run Code Online (Sandbox Code Playgroud)


小智 5

借助 Spring Data,您可以使用 MongoTemplate 或 MongoOperations 以编程方式创建索引

    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));
Run Code Online (Sandbox Code Playgroud)