排序规则提供了一设立规则,可在比较符合特定语言(例如西班牙语或德语)惯例的字符串时使用。 如果未指定排序规则,服务器将根据二进制比较对字符串进行排序。 但是,许多语言都有特定的排序规则,排序规则允许用户构建遵循这些规则的应用程序。
示例,在法语中,给定单词中的最后一个重音决定了排序顺序。 以下示例显示了法语中四个单词的正确排序顺序:
cote < côte < coté < côté
指定法语排序规则允许用户使用法语排序顺序对string字段进行排序。
使用
您可以为 集合、索引或CRUD命令指定排序规则。
排序规则参数:
您可以使用 ~pymongo.collation.Collation
模型或Python字典来指定排序规则。 无论哪种情况,结构都是相同的:
Collation(locale=<string>, caseLevel=<bool>, caseFirst=<string>, strength=<int>, numericOrdering=<bool>, alternate=<string>, maxVariable=<string>, backwards=<bool>)
唯一必需的参数是locale
,服务器会将其解析为ICU 格式的区域设置ID 。 示例,设立locale
设置为en_US
以代表美国英语,或将 fr_CA
设置为以代表加拿大法语。
为collection指定默认排序规则
以下示例演示了如何创建名为contacts
的新集合,并分配具有fr_CA
区域设置的默认排序规则。 除非显式指定了其他排序规则,否则此操作可确保针对contacts
集合运行的所有查询都使用fr_CA
排序规则。
from pymongo import MongoClient from pymongo.collation import Collation db = MongoClient().test collection = db.create_collection('contacts', collation=Collation(locale='fr_CA'))
为索引指定默认排序规则
创建新索引时,可以指定默认排序规则。
以下示例展示了如何在启用unique
参数并将默认排序规则(将locale
设立为fr_CA
的情况下对contacts
集合的name
字段创建索引。
from pymongo import MongoClient from pymongo.collation import Collation contacts = MongoClient().test.contacts contacts.create_index('name', unique=True, collation=Collation(locale='fr_CA'))
为查询指定排序规则
查询可以指定对结果进行排序时使用的排序规则。 以下示例演示了对test
数据库中的contacts
集合运行的查询。 它匹配city
字段中包含New York
的文档,并使用fr_CA
排序规则对name
字段进行排序。
from pymongo import MongoClient from pymongo.collation import Collation collection = MongoClient().test.contacts docs = collection.find({'city': 'New York'}).sort('name').collation( Collation(locale='fr_CA'))
其他查询类型
您可以使用排序规则来控制几种不同类型查询的文档匹配规则。 所有执行更新或删除操作的方法都支持排序规则,您可以创建查询筛选器,使用排序规则来遵循locale
参数可用的任何语言和变体。
以下示例使用将 strength
设立为 ~pymongo.collation.CollationStrength.SECONDARY
的排序规则,该排序规则在string比较中仅考虑基本字符和重音字符,而不考虑大小写,示例。 contacts
集合中first_name
字段包含jürgen
(不区分大小写)的所有文档均会更新。
from pymongo import MongoClient from pymongo.collation import Collation, CollationStrength contacts = MongoClient().test.contacts result = contacts.update_many( {'first_name': 'jürgen'}, {'$set': {'verified': 1}}, collation=Collation(locale='de', strength=CollationStrength.SECONDARY))