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

索引和集合管理

MongoTemplateReactiveMongoTemplate提供管理索引和集合的方法。 这些方法被收集到一个名为IndexOperations分别ReactiveIndexOperations. 您可以通过调用indexOps方法并传入集合名称或java.lang.Class的 Git(集合名称派生自.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();
}

创建索引的方法

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

template.indexOps(Person.class)
    .ensureIndex(new Index().on("name",Order.ASCENDING));

ensureIndex确保集合存在提供的 IndexDefinition 的索引。spring-doc.cadn.net.cn

您可以使用IndexDefinition,GeoSpatialIndexTextIndexDefinition类。 例如,给定Venue类,您可以声明地理空间查询,如下例所示:spring-doc.cadn.net.cn

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

访问索引信息

IndexOperationsinterface 具有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();

使用集合的方法

以下示例显示如何创建集合:spring-doc.cadn.net.cn

MongoCollection<Document> collection = null;
if (!template.getCollectionNames().contains("MyNewCollection")) {
    collection = mongoTemplate.createCollection("MyNewCollection");
}
集合创建允许使用CollectionOptions并支持排序规则
与 MongoCollections 交互的方法

时间序列

MongoDB 5.0 引入了时间序列集合,这些集合经过优化,可以随着时间的推移有效地存储文档,例如测量或事件。 在插入任何数据之前,需要按原样创建这些集合。 可以通过运行createCollection命令、定义时间序列集合选项或从@TimeSeriesannotation 中,如以下示例所示。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"));
创建从 Annotation 派生的 Time Series Collection
@TimeSeries(collection="weather", timeField = "timestamp")
public class Measurement {

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

template.createCollection(Measurement.class);

上面的代码片段可以很容易地转移到提供完全相同方法的反应式 API 中。 确保正确订阅返回的发布者。spring-doc.cadn.net.cn

您可以使用@TimeSeries#expireAfter选项让 MongoDB 自动删除过期的存储桶。 该属性允许不同的超时格式,例如10s,3h,...以及表达式 (#{@mySpringBean.timeout}) 和属性占位符 (${my.property.timeout}) 语法。spring-doc.cadn.net.cn


APP信息