跳到主要内容
版本:5.1.1

索引与集合管理

Doubao 中英对照 Index and Collection Management

MongoTemplate 和 ReactiveMongoTemplate 提供了用于管理索引和集合的方法。这些方法被分别归集到名为 IndexOperations 和 ReactiveIndexOperations 的辅助接口中。您可以通过调用 indexOps 方法并传入集合名称或您实体的 java.lang.Class 来访问这些操作(集合名称派生自该 .class,要么按名称派生,要么从注解元数据派生)。

以下清单展示了 IndexOperations 接口:

public interface IndexOperations {

String ensureIndex(IndexDefinition indexDefinition);

void alterIndex(String name, IndexOptions options);

void dropIndex(String name);

void dropAllIndexes();

List<IndexInfo> getIndexInfo();
}

创建索引的方法​

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

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

ensureIndex 确保集合上存在针对所提供 IndexDefinition 的索引。

您可以使用 IndexDefinition、GeoSpatialIndex 和 TextIndexDefinition 类来创建标准索引、地理空间索引和文本索引。例如,给定前一节中定义的 Venue 类,您可以声明一个地理空间查询,如下例所示:

template.indexOps(Venue.class)
.ensureIndex(new GeospatialIndex("location"));
备注

Index 和 GeospatialIndex 支持配置排序规则。

访问索引信息​

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

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

List<IndexInfo> indexInfoList = template.indexOps(Person.class)
.getIndexInfo();

操作集合的方法​

以下示例展示了如何创建集合:

MongoCollection<Document> collection = null;
if (!template.getCollectionNames().contains("MyNewCollection")) {
collection = mongoTemplate.createCollection("MyNewCollection");
}
备注

创建集合时可以通过 CollectionOptions 进行自定义,并支持排序规则。

与 MongoCollection 交互的方法

  • getCollectionNames: 返回一个集合名称集合。

  • collectionExists: 检查是否存在具有给定名称的集合。

  • createCollection: 创建一个非固定大小集合。

  • dropCollection: 丢弃该集合。

  • getCollection: 按名称获取集合;如果集合不存在则创建它。

时间序列​

MongoDB 5.0 引入了时间序列集合,这类集合经过优化,可高效地随时间存储文档,例如度量值或事件。在插入任何数据之前,需要先将这些集合创建为时间序列集合。可以通过运行 createCollection 命令、定义时间序列集合选项,或从 @TimeSeries 注解中提取选项来创建集合,如下例所示。

示例 1. 创建时间序列集合

template.execute(db -> {

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

db.createCollection("weather", options);
return "OK";
});
template.createCollection("weather", CollectionOptions.timeSeries("timestamp"));
@TimeSeries(collection="weather", timeField = "timestamp")
public class Measurement {

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

template.createCollection(Measurement.class);

以上代码片段可以很容易地迁移到提供完全相同方法的响应式 API。请务必正确地 订阅 返回的发布器。

提示

您可以使用 @TimeSeries#expireAfter 选项,让 MongoDB 自动移除过期的存储桶。该属性支持多种超时格式,例如 10s、3h…​,以及表达式(#{@mySpringBean.timeout})和属性占位符(${my.property.timeout})语法。