此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Data MongoDB 5.0.4spring-doc.cadn.net.cn

索引与集合管理

MongoTemplateReactiveMongoTemplate 提供了用于管理索引和集合的方法。 这些方法分别被收集到一个名为 IndexOperationsReactiveIndexOperations 的辅助接口中。 你可以通过调用 indexOps 方法并传入集合名称或实体的 java.lang.Class(集合名称将从 .class 中派生,既可以基于类名,也可以基于注解元数据)来访问这些操作。spring-doc.cadn.net.cn

以下代码清单展示了 IndexOperations 接口:spring-doc.cadn.net.cn

public interface IndexOperations {

    String ensureIndex(IndexDefinition indexDefinition);

    void alterIndex(String name, IndexOptions options);

    void dropIndex(String name);

    void dropAllIndexes();

    List<IndexInfo> getIndexInfo();
}
public interface ReactiveIndexOperations {

    Mono<String> ensureIndex(IndexDefinition indexDefinition);

    Mono<Void> alterIndex(String name, IndexOptions options);

    Mono<Void> dropIndex(String name);

    Mono<Void> dropAllIndexes();

    Flux<IndexInfo> getIndexInfo();

创建索引的方法

您可以使用 MongoTemplate 类在集合上创建索引,以提升查询性能,如下例所示:spring-doc.cadn.net.cn

template.indexOps(Person.class)
    .ensureIndex(new Index().on("name",Order.ASCENDING));
Mono<String> createIndex = template.indexOps(Person.class)
    .ensureIndex(new Index().on("name",Order.ASCENDING));

ensureIndex 确保为集合中提供的 IndexDefinition 创建了索引。spring-doc.cadn.net.cn

你可以使用 IndexDefinitionGeoSpatialIndexTextIndexDefinition 类来创建标准索引、地理空间索引和文本索引。 例如,对于前一节中定义的 Venue 类,你可以声明一个地理空间查询,如下例所示:spring-doc.cadn.net.cn

template.indexOps(Venue.class)
    .ensureIndex(new GeospatialIndex("location"));
IndexGeospatialIndex 支持配置排序规则

访问索引信息

IndexOperations 接口提供了 getIndexInfo 方法,该方法返回一个 IndexInfo 对象列表。 此列表包含在集合上定义的所有索引。以下示例在具有 Person 属性的 age 类上定义了一个索引:spring-doc.cadn.net.cn

template.indexOps(Person.class)
    .ensureIndex(new Index().on("age", Order.DESCENDING).unique());

List<IndexInfo> indexInfoList = template.indexOps(Person.class)
   .getIndexInfo();
Mono<String> ageIndex = template.indexOps(Person.class)
    .ensureIndex(new Index().on("age", Order.DESCENDING).unique());

Flux<IndexInfo> indexInfo = ageIndex.then(template.indexOps(Person.class)
   .getIndexInfo());

处理集合的方法

以下示例展示了如何创建一个集合:spring-doc.cadn.net.cn

MongoCollection<Document> collection = null;
if (!template.getCollectionNames().contains("MyNewCollection")) {
    collection = mongoTemplate.createCollection("MyNewCollection");
}
MongoCollection<Document> collection = template.getCollectionNames().collectList()
    .flatMap(collectionNames -> {
        if(!collectionNames.contains("MyNewCollection")) {
            return template.createCollection("MyNewCollection");
        }
        return template.getMongoDatabase().map(db -> db.getCollection("MyNewCollection"));
    });
集合创建允许使用 CollectionOptions 进行自定义,并支持排序规则
用于与 MongoCollection 交互的方法

时间序列

MongoDB 5.0 引入了时间序列集合,该集合经过优化,可高效地按时间顺序存储文档,例如测量数据或事件。 在插入任何数据之前,必须先将这些集合作为时间序列集合进行创建。 可以通过执行createCollection命令、定义时间序列集合选项,或从@TimeSeries注解中提取选项来创建集合,如下方示例所示。spring-doc.cadn.net.cn

示例 1. 创建一个时间序列集合
通过 MongoDB 驱动程序创建时间序列
template.execute(db -> {

    com.mongodb.client.model.CreateCollectionOptions options = new CreateCollectionOptions();
    options.timeSeriesOptions(new TimeSeriesOptions("timestamp"));

    db.createCollection("weather", options);
    return "OK";
});
使用 CollectionOptions 创建时间序列集合
template.createCollection("weather", CollectionOptions.timeSeries("timestamp"));
根据注解创建一个时间序列集合
@TimeSeries(collection="weather", timeField = "timestamp")
public class Measurement {

    String id;
    Instant timestamp;
    // ...
}

template.createCollection(Measurement.class);

上面的代码片段可以轻松迁移到响应式 API,后者提供了完全相同的方法。 请确保对返回的发布者(publishers)正确地进行订阅spring-doc.cadn.net.cn

您可以使用 @TimeSeries#expireAfter 选项,让 MongoDB 自动删除已过期的数据桶(buckets)。 该属性支持多种超时格式,例如 10s3h……,同时也支持表达式语法(#{@mySpringBean.timeout})和属性占位符语法(${my.property.timeout})。spring-doc.cadn.net.cn