On this page本页内容
$sort
Sorts all input documents and returns them to the pipeline in sorted order.对所有输入文档进行排序,并按排序顺序将其返回到管道。
The $sort
stage has the following prototype form:$sort
阶段具有以下原型形式:
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
$sort
takes a document that specifies the field(s) to sort by and the respective sort order. 获取指定要排序的字段和相应排序顺序的文档。<sort order>
can have one of the following values:可以具有以下值之一:
1 | |
-1 | |
{ $meta: "textScore" } | textScore metadata in descending order. textScore 元数据降序排序。 |
If sorting on multiple fields, sort order is evaluated from left to right. 如果对多个字段进行排序,则从左到右计算排序顺序。For example, in the form above, documents are first sorted by 例如,在上面的表单中,文档首先按<field1>
. <field1>
排序。Then documents with the same 然后,具有相同<field1>
values are further sorted by <field2>
.<field1>
值的文档将按<field2>
进一步排序。
You can sort on a maximum of 32 keys.最多可以按32个键排序。
MongoDB does not store documents in a collection in a particular order. MongoDB不按特定顺序存储集合中的文档。When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.在对包含重复值的字段进行排序时,包含这些值的文档可以按任何顺序返回。
If consistent sort order is desired, include at least one field in your sort that contains unique values. 如果需要一致的排序顺序,请在排序中至少包含一个包含唯一值的字段。The easiest way to guarantee this is to include the 保证这一点的最简单方法是在排序查询中包含_id
field in your sort query._id
字段。
Consider the following 考虑以下restaurant
collection:restaurant
集合:
db.restaurants.insertMany( [ { "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"}, { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"}, { "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"}, { "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"}, { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"}, ] );
The following command uses the 以下命令使用$sort
stage to sort on the borough
field:$sort
阶段对borough
字段进行排序:
db.restaurants.aggregate( [ { $sort : { borough : 1 } } ] )
In this example, sort order may be inconsistent, since the 在本例中,排序顺序可能不一致,因为borough
field contains duplicate values for both Manhattan
and Brooklyn
. borough
字段包含Manhattan
和Brooklyn
的重复值。Documents are returned in alphabetical order by 文档按borough
, but the order of those documents with duplicate values for borough
might not the be the same across multiple executions of the same sort. borough
的字母顺序返回,但在相同排序的多个执行中,具有重复borough
值的文档的顺序可能不同。For example, here are the results from two different executions of the above command:例如,以下是上述命令的两次不同执行的结果:
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" } { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" } { "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" } { "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" } { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" } { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" } { "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" } { "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" } { "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" } { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" }
While the values for 虽然borough
are still sorted in alphabetical order, the order of the documents containing duplicate values for borough
(i.e. Manhattan
and Brooklyn
) is not the same.borough
的值仍按字母顺序排序,但包含borough
(即Manhattan
和Brooklyn
)重复值的文档的顺序并不相同。
To achieve a consistent sort, add a field which contains exclusively unique values to the sort. 要实现一致排序,请在排序中添加包含唯一值的字段。The following command uses the 以下命令使用$sort
stage to sort on both the borough
field and the _id
field:$sort
阶段对borough
字段和_id
字段进行排序:
db.restaurants.aggregate( [ { $sort : { borough : 1, _id: 1 } } ] )
Since the 由于_id
field is always guaranteed to contain exclusively unique values, the returned sort order will always be the same across multiple executions of the same sort._id
字段始终保证包含唯一的值,因此在同一排序的多个执行中,返回的排序顺序始终相同。
For the field or fields to sort by, set the sort order to 对于要排序的一个或多个字段,将排序顺序设置为1
or -1
to specify an ascending or descending sort respectively, as in the following example:1
或-1
以分别指定升序或降序排序,如以下示例所示:
db.users.aggregate( [ { $sort : { age : -1, posts: 1 } } ] )
This operation sorts the documents in the 此操作将users
collection, in descending order according by the age
field and then in ascending order according to the value in the posts
field.users
集合中的文档按age
字段降序排序,然后按posts
字段中的值升序排序。
When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest:当比较不同BSON类型的值时,MongoDB使用以下比较顺序,从最低到最高:
For details on the comparison/sort order for specific types, see Comparison/Sort Order.有关特定类型的比较/排序顺序的详细信息,请参阅比较/排序次序。
For a pipeline that includes a 对于包含$text
search, you can sort by descending relevance score using the { $meta: "textScore" }
expression. $text
搜索的管道,可以使用{ $meta: "textScore" }
表达式按相关性得分降序排序。In the 在{ <sort-key> }
document, set the { $meta: "textScore" }
expression to an arbitrary field name. {<sort key>}
文档中,将{ $meta: "textScore" }
表达式设置为任意字段名。The field name is ignored by the query system. 查询系统将忽略字段名。For example:例如:
db.users.aggregate( [ { $match: { $text: { $search: "operating" } } }, { $sort: { score: { $meta: "textScore" }, posts: -1 } } ] )
This operation uses the 此操作使用$text
operator to match the documents, and then sorts first by the "textScore"
metadata in descending order, and then by the posts
field in descending order. $text
运算符来匹配文档,然后首先按"textScore"
元数据降序排序,然后按posts
字段降序排序。The 查询系统将忽略排序文档中的score
field name in the sort document is ignored by the query system. score
字段名称。In this pipeline, the 在这个管道中,"textScore"
metadata is not included in the projection and is not returned as part of the matching documents. "textScore"
元数据不包括在投影中,也不作为匹配文档的一部分返回。See 有关详细信息,请参阅$meta
for more information.$meta
。
$sort
$sort
+ $limit
When a 当$sort
precedes a $limit
and there are no intervening stages that modify the number of documents, the optimizer can coalesce the $limit
into the $sort
. $sort
在$limit
之前,并且没有修改文档数量的中间阶段时,优化器可以将$limit
合并到$sort
中。This allows the 这允许$sort
operation to only maintain the top n
results as it progresses, where n
is the specified limit, and ensures that MongoDB only needs to store n
items in memory. $sort
操作在运行过程中只维护前n
个结果,其中n
是指定的限制,并确保MongoDB只需要在内存中存储n
个项。This optimization still applies when 当allowDiskUse
is true
and the n
items exceed the aggregation memory limit.allowDiskUse
为true
且n
项超过聚合内存限制时,此优化仍然适用。
Optimizations are subject to change between releases.优化可能会在不同版本之间发生变化。
$sort
The $sort
stage has a limit of 100 megabytes of RAM for in-memory sorts. $sort
阶段的内存排序限制为100兆字节。By default, if the stage exceeds this limit, 默认情况下,如果阶段超过此限制,$sort
produces an error. $sort
将产生错误。To allow pipeline processing to take up more space, use the 要允许管道处理占用更多空间,请使用allowDiskUse
option to enable aggregation pipeline stages to write data to temporary files.allowDiskUse
选项启用聚合管道阶段将数据写入临时文件。
$sort
The $sort
operator can take advantage of an index if it's used in the first stage of a pipeline or if it's only preceeded by a $match
stage.$sort
运算符可以利用索引,如果它用于管道的第一阶段,或者如果它只在$match
阶段之前。
When you use the 在分片集群上使用$sort
on a sharded cluster, each shard sorts its result documents using an index where available. $sort
时,每个分片都使用索引(如果可用)对其结果文档进行排序。Then the 然后,mongos
or one of the shards performs a streamed merge sort.mongos
或其中一个分片执行流式合并排序。