Docs HomeMongoDB Manual

$sort (aggregation)

Definition定义

$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:可以具有以下值之一:

ValueDescription描述
1Sort ascending.按升序排序。
-1Sort descending.按降序排序。
{ $meta: "textScore" }Sort by the computed textScore metadata in descending order. 按计算的textScore元数据降序排序。See Text Score Metadata Sort for an example.有关示例,请参阅文本分数元数据排序

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>进一步排序。

Behavior行为

Limits限制

You can sort on a maximum of 32 keys.最多可以对32个键进行排序。

Sort Consistency排序一致性

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.MongoDB不会按特定顺序将文档存储在集合中。对包含重复值的字段进行排序时,可以按任何顺序返回包含这些值的文档。

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字段包含ManhattanBrooklyn的重复值。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按字母顺序返回,但在同一类别的多个执行中,具有重复自治区值的文档的顺序可能不相同。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(即ManhattanBrooklyn)重复值的文档的顺序不同。

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中添加一个包含唯一值的字段。以下命令使用$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字段始终保证包含唯一值,因此在同一排序的多个执行中,返回的排序顺序始终相同。

Examples实例

Ascending/Descending Sort升序/降序排序

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.此操作根据age字段按降序对users集合中的文档进行排序,然后根据posts字段中的值按升序对文档进行排序。

When comparing values of different BSON types in sort operations, MongoDB uses the following comparison order, from lowest to highest:在排序操作中比较不同BSON类型的值时,MongoDB使用以下比较顺序,从低到高:

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles, decimals)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)

For details on the comparison/sort order for specific types, see Comparison/Sort Order.有关特定类型的比较/排序顺序的详细信息,请参阅比较/排序次序

Text Score Metadata Sort文本分数元数据排序

For a pipeline that includes a $text search, you can sort by descending relevance score using the { $meta: "textScore" } expression. In the { <sort-key> } document, set the { $meta: "textScore" } expression to an arbitrary field name. 对于包含$text搜索的管道,可以使用{ $meta: "textScore" }表达式按相关性分数降序进行排序。在{ <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 Operator and Memory运算符和内存

$sort + $limit Memory Optimization内存优化

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.allowDiskUsetrue并且n个项目超过聚合内存限制时,此优化仍然适用。

Optimizations are subject to change between releases.优化可能会在不同版本之间发生变化。

$sort and Memory Restrictions和内存限制

$sort is subject to the 100 megabyte memory usage limit, but is able to write temporary files to disk if additional space is required.受100兆字节内存使用限制,但如果需要额外空间,可以将临时文件写入磁盘。

Starting in MongoDB 6.0, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. 从MongoDB 6.0开始,需要超过100MB内存才能执行的管道阶段默认情况下会将临时文件写入磁盘。In earlier verisons of MongoDB, you must pass { allowDiskUse: true } to individual find and aggregate commands to enable this behavior.在MongoDB的早期版本中,必须将{ allowDiskUse: true }传递给单个findaggregate命令才能启用此行为。

Individual find and aggregate commands may override the allowDiskUseByDefault parameter by either:单独的findaggregate命令可以通过以下方式覆盖allowDiskUseByDefault参数:

  • Using { allowDiskUse: true } to allow writing temporary files out to disk when allowDiskUseByDefault is set to false使用{ allowDiskUse: true }allowDiskUseByDefault设置为false时,允许将临时文件写入磁盘
  • Using { allowDiskUse: false } to prohibit writing temporary files out to disk when allowDiskUseByDefault is set to true使用{ allowDiskUse: false }allowDiskUseByDefault设置为true时,禁止将临时文件写入磁盘
Tip

$sort Operator and Performance运算符和性能

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.如果在管道的第一阶段中使用索引,或者仅在索引前面有$match阶段,则$sort运算符可以利用索引。

When you use the $sort on a sharded cluster, each shard sorts its result documents using an index where available. Then the mongos or one of the shards performs a streamed merge sort.当您在分片集群上使用$sort时,每个分片都会使用可用的索引对其结果文档进行排序。然后mongos或其中一个分片执行流式合并排序。