排序规则
从 3.4 版本开始,MongoDB 支持在集合和索引创建以及各种查询操作中使用排序规则。排序规则定义了基于 ICU 排序规则的字符串比较规则。一个排序规则文档包含多种属性,这些属性封装在 Collation
对象中,如下所示
Collation collation = Collation.of("fr") (1)
.strength(ComparisonLevel.secondary() (2)
.includeCase())
.numericOrderingEnabled() (3)
.alternate(Alternate.shifted().punct()) (4)
.forwardDiacriticSort() (5)
.normalizationEnabled(); (6)
1 | Collation 的创建需要一个区域设置。这可以是区域设置的字符串表示、Locale (考虑语言、国家和变体)或 CollationLocale 。区域设置是创建时必需的。 |
2 | 排序规则强度定义了表示字符之间差异的比较级别。您可以根据所选的强度配置各种选项(区分大小写、大小写顺序等)。 |
3 | 指定是按数字还是按字符串比较数字字符串。 |
4 | 指定排序规则在比较时是否应将空格和标点符号视为基本字符。 |
5 | 指定带变音符号的字符串是否从字符串末尾开始排序,例如某些法语词典排序。 |
6 | 指定是否检查文本是否需要规范化以及是否执行规范化。 |
排序规则可用于创建集合和索引。如果您创建了一个指定排序规则的集合,除非您指定不同的排序规则,否则该排序规则将应用于索引创建和查询。排序规则对整个操作有效,不能按字段指定。
与其他元数据一样,排序规则可以通过 `@Document` 注解的 `collation` 属性从域类型派生,并在运行查询、创建集合或索引时直接应用。
当集合在第一次交互时由 MongoDB 自动创建时,不会使用注解指定的排序规则。这需要额外的存储交互,会延迟整个过程。对于这些情况,请使用 `MongoOperations.createCollection`。 |
Collation french = Collation.of("fr");
Collation german = Collation.of("de");
template.createCollection(Person.class, CollectionOptions.just(collation));
template.indexOps(Person.class).ensureIndex(new Index("name", Direction.ASC).collation(german));
如果未指定排序规则,MongoDB 会使用简单的二进制比较 (`Collation.simple()`)。 |
在集合操作中使用排序规则,只需在查询或操作选项中指定一个 `Collation` 实例,如下面两个示例所示
示例 1. 在 `find` 中使用排序规则
Collation collation = Collation.of("de");
Query query = new Query(Criteria.where("firstName").is("Amél")).collation(collation);
List<Person> results = template.find(query, Person.class);
示例 2. 在 `aggregate` 中使用排序规则
Collation collation = Collation.of("de");
AggregationOptions options = AggregationOptions.builder().collation(collation).build();
Aggregation aggregation = newAggregation(
project("tags"),
unwind("tags"),
group("tags")
.count().as("count")
).withOptions(options);
AggregationResults<TagCount> results = template.aggregate(aggregation, "tags", TagCount.class);
仅当操作使用的排序规则与索引排序规则匹配时,才会使用索引。 |
MongoDB Repositories 通过 `@Query` 注解的 `collation` 属性支持 `Collations`。