Index and Collection Management
MongoTemplate
和 ReactiveMongoTemplate
提供了用于管理索引和集合的方法。这些方法分别收集到名为 IndexOperations
和 ReactiveIndexOperations
的帮助程序接口中。你可以通过调用 indexOps
方法并传入实体的集合名称或 java.lang.Class
来访问这些操作(集合名称从 .class
派生,通过名称或注释元数据派生)。
MongoTemplate
and ReactiveMongoTemplate
provide methods for managing indexes and collections.
These methods are collected into a helper interface called IndexOperations
respectively ReactiveIndexOperations
.
You can access these operations by calling the indexOps
method and passing in either the collection name or the java.lang.Class
of your entity (the collection name is derived from the .class
, either by name or from annotation metadata).
以下列表显示了 IndexOperations
接口:
The following listing shows the IndexOperations
interface:
-
Imperative
-
Reactive
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();
Methods for Creating an Index
你可以使用 MongoTemplate 类在集合上创建索引以改进查询性能,如下例所示:
You can create an index on a collection to improve query performance by using the MongoTemplate class, as the following example shows:
-
Imperative
-
Reactive
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 的索引。
ensureIndex
makes sure that an index for the provided IndexDefinition exists for the collection.
可以利用 IndexDefinition
、GeoSpatialIndex
和 TextIndexDefinition
类创建标准、地理空间和文本索引。例如,假设在之前的部分中已定义了 Venue
类,那么你可以声明一个地理空间查询,如下例所示:
You can create standard, geospatial, and text indexes by using the IndexDefinition
, GeoSpatialIndex
and TextIndexDefinition
classes.
For example, given the Venue
class defined in a previous section, you could declare a geospatial query, as the following example shows:
template.indexOps(Venue.class)
.ensureIndex(new GeospatialIndex("location"));
|
|
Accessing Index Information
IndexOperations
接口具有 getIndexInfo
方法,返回 IndexInfo
对象列表。此列表包含在集合上定义的所有索引。以下示例在拥有 age
属性的 Person
类上定义了一个索引:
The IndexOperations
interface has the getIndexInfo
method that returns a list of IndexInfo
objects.
This list contains all the indexes defined on the collection. The following example defines an index on the Person
class that has an age
property:
-
Imperative
-
Reactive
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());
Methods for Working with a Collection
以下示例展示了如何创建集合:
The following example shows how to create a collection:
-
Imperative
-
Reactive
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` 进行定制,并支持collations。 |
Collection creation allows customization with |
-
getCollectionNames: Returns a set of collection names.
-
collectionExists: Checks to see if a collection with a given name exists.
-
createCollection: Creates an uncapped collection.
-
dropCollection: Drops the collection.
-
getCollection: Gets a collection by name, creating it if it does not exist.
Time Series
MongoDB 5.0 引入了 Time Series 集合,这些集合经过优化,可以随着时间的推移有效存储文档,例如测量或事件。在插入任何数据之前,需要按此方式创建这些集合。可以通过运行 createCollection
命令、定义时间序列集合选项或从 @TimeSeries
注释中提取选项(如下面的示例所示)来创建集合。
MongoDB 5.0 introduced Time Series collections that are optimized to efficiently store documents over time such as measurements or events.
Those collections need to be created as such before inserting any data.
Collections can be created by either running the createCollection
command, defining time series collection options or extracting options from a @TimeSeries
annotation as shown in the examples below.
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,提供完全相同的方法。请确保正确 订阅 返回的发布者。
The snippets above can easily be transferred to the reactive API offering the very same methods. Make sure to properly subscribe to the returned publishers.