Database Manual / Reference / mongosh Methods / Cursors

cursor.sort() (mongosh method方法)

Definition定义

cursor.sort(sort)

Important

mongosh Method方法

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.本页记录了一种mongosh方法。这不是针对特定语言驱动程序(如Node.js)的文档。

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档

Specifies the order in which the query returns matching documents. You must apply sort() to the cursor before retrieving any documents from the database.指定查询返回匹配文档的顺序。在从数据库检索任何文档之前,必须对游标应用sort()

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The sort() method has the following parameter:sort()方法有以下参数:

Parameter参数Type类型Description描述
sortdocument文档A document that defines the sort order of the result set.定义结果集排序顺序的文档。

The sort parameter contains field and value pairs, in the following form:sort参数包含字段和值对,格式如下:

{ field: value }

The sort document can specify ascending or descending sort on existing fields or sort on text score metadata.排序文档可以对现有字段指定升序或降序排序,也可以对文本分数元数据进行排序

Behavior行为

Limits限制

  • You can sort on a maximum of 32 keys.您最多可以对32个键进行排序。
  • Providing a sort pattern with duplicate fields causes an error.提供具有重复字段的排序模式会导致错误。

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不会以特定顺序将文档存储在集合中。在对包含重复值的字段进行排序时,包含这些值的文档可以按任何顺序返回。

The $sort operation is not a "stable sort," which means that documents with equivalent sort keys are not guaranteed to remain in the same relative order in the output as they were in the input.$sort操作不是“稳定排序”,这意味着具有等效排序键的文档不能保证在输出中保持与输入中相同的相对顺序。

If the field specified in the sort criteria does not exist in two documents, then the value on which they are sorted is the same. The two documents 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() method to sort on the borough field:以下命令使用sort()方法对borough字段进行排序:

db.restaurants.find().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 be the same across multiple executions of the same sort. For example, here are the results from two different executions of the above command:文档按borough按字母顺序返回,但borough值重复的文档在同一排序的多个执行中的顺序可能不同。例如,以下是上述命令的两次不同执行的结果:

{ _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() method to sort on both the borough field and the _id field:为了实现一致的排序,请在排序中添加一个仅包含唯一值的字段。以下命令使用sort()方法对borough字段和_id字段进行排序:

db.restaurants.find().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字段总是保证只包含唯一值,因此返回的排序顺序在同一排序的多个执行中总是相同的。

Important

When sorting by a nonexistent field, MongoDB does not guarantee any particular output ordering. The behavior in these cases may change from version to version.当按不存在的字段排序时,MongoDB不保证任何特定的输出顺序。在这些情况下,行为可能会因版本而异。

Ascending/Descending Sort升序/降序排序

Specify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively.在排序参数中指定要排序的一个或多个字段,并指定值1-1以分别指定升序或降序。

The following operation sorts the documents first by the age field in descending order and then by the posts field in ascending order:以下操作首先按age字段降序排列文档,然后按posts字段升序排列文档:

db.users.find({ }).sort( { age : -1, posts: 1 } )

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. JavaScript Code
  14. JavaScript Code with Scope
  15. MaxKey (internal type)

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

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

Note

$text provides text query capabilities for self-managed (non-Atlas) deployments. 为自我管理(非Atlas)部署提供文本查询功能。For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search.对于托管在MongoDB上的数据,MongoDB还提供了改进的全文查询解决方案MongoDB搜索

If you use $text, you can sort by descending relevance score using the { $meta: "textScore" } expression.如果使用$text,则可以使用{ $meta: "textScore" }表达式按相关性得分降序排序。

The following sample document specifies a descending sort by the "textScore" metadata:以下示例文档按"textScore"元数据指定降序排序:

db.users.find(
{ $text: { $search: "operating" } },
{ score: { $meta: "textScore" }}
).sort({ score: { $meta: "textScore" } })

The "textScore" metadata sorts in descending order."textScore"元数据按降序排列。

For more information, see $meta for details.有关详细信息,请参阅$meta

Sort by an Array Field按数组字段排序

When MongoDB sorts documents by an array-value field, the sort key depends on whether the sort is ascending or descending:当MongoDB按数组值字段对文档进行排序时,排序键取决于排序是升序还是降序:

  • In an ascending sort, the sort key is the lowest value in the array.在升序排序中,排序键是数组中的最低值。
  • In a descending sort, the sort key is the highest value in the array.在降序排序中,排序键是数组中的最高值。

The query filter does not affect sort key selection.查询筛选器不影响排序键选择。

For example, create a shoes collection with these documents:例如,使用以下文档创建shoes集合:

db.shoes.insertMany( [
{ _id: 'A', sizes: [ 7, 11 ] },
{ _id: 'B', sizes: [ 8, 9, 10 ] }
] )

The following queries sort the documents by the sizes field in ascending and descending order:以下查询按sizes字段按升序和降序对文档进行排序:

// Ascending sort
db.shoes.find().sort( { sizes: 1 } )

// Descending sort
db.shoes.find().sort( { sizes: -1 } )

Both of the preceding queries return the document with _id: 'A' first because sizes 7 and 11 are the lowest and highest in the entries in the sizes array, respectively.前面的两个查询都首先返回_id: 'A'的文档,因为大小711分别是大小数组中条目的最低和最高值。

Filter and Sort by an Array Field按数组字段筛选和排序

When you filter and sort by a field that contains an array, the filter does not affect the value used as the sort key. The sort always considers all array values as potential sort keys.当您根据包含数组的字段进行筛选和排序时,筛选不会影响用作排序键的值。排序总是将所有数组值视为潜在的排序键。

For example, the following query finds shoes with sizes greater than 9 and sorts the results by size in ascending order:例如,以下查询查找尺寸大于9的鞋子,并按尺寸升序对结果进行排序:

db.shoes.find( { sizes: { $gt: 9 } } ).sort( { sizes: 1 } )

The sort is ascending, which means that the sort key is the lowest value in the sizes array:排序是升序的,这意味着排序键是sizes数组中的最低值:

  • In document _id: 'A', the lowest sizes element is 7. 在文档_id: 'A'中,最小的sizes元素是7This value is used as the sort key even though it does not match the filter { sizes: { $gt: 9 }.即使此值与筛选器{ sizes: { $gt: 9 }不匹配,它也会用作排序键。
  • In document _id: 'B', the lowest sizes element is 8. Similarly, this value is used as the sort key even though it does not match the filter.在文档_id: 'B'中,最小sizes的元素是8。同样,即使该值与筛选器不匹配,也会将其用作排序键。

The query returns the document with _id: 'A' first.查询首先返回_id: 'A'的文档。

Tip

Sort only by Matched Values仅按匹配值排序

To only consider matched values as potential sort keys, you can generate a new field containing the matched values and sort on that field. For more information, see these pipeline stages and expressions:为了只将匹配的值视为潜在的排序键,您可以生成一个包含匹配值的新字段,并对该字段进行排序。有关更多信息,请参阅以下管道阶段和表达式:

Sort and Index Use排序和索引使用

MongoDB can obtain the results of a sort operation from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.MongoDB可以从包含排序字段的索引中获取排序操作的结果。如果排序使用与查询谓词相同的索引,MongoDB可能会使用多个索引来支持排序操作。

If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform an in-memory sort operation on the data.如果MongoDB无法使用一个或多个索引来获取排序顺序,则MongoDB必须对数据执行内存中的排序操作。

Sort operations that use an index often have better performance than in-memory sorts. For more information on creating indexes to support sort operations, see Use Indexes to Sort Query Results.使用索引的排序操作通常比内存中的排序具有更好的性能。有关创建索引以支持排序操作的更多信息,请参阅使用索引对查询结果进行排序

To check if MongoDB must perform an in-memory sort, append cursor.explain() to the query and check the explain results. 要检查MongoDB是否必须执行内存排序,请将cursor.explain()附加到查询中并检查解释结果If the query plan contains a SORT stage, then MongoDB must perform an in-memory sort operation.如果查询计划包含SORT阶段,则MongoDB必须执行内存中的排序操作。

To prevent in-memory sorts from consuming too much memory:要防止内存中的排序消耗太多内存:

Limit Results限制结果

You can use sort() in conjunction with limit() to return the first (in terms of the sort order) k documents, where k is the specified limit.您可以将sort()limit()结合使用,以返回第一个(按排序顺序)k个文档,其中k是指定的限制。

If MongoDB cannot obtain the sort order via an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first k results (or last, depending on the sort order) seen so far by the underlying index or collection access. 如果MongoDB无法通过索引扫描获得排序顺序,则MongoDB使用top-k排序算法。该算法缓冲底层索引或集合访问到目前为止看到的前k个结果(或最后一个,取决于排序顺序)。If at any point the memory footprint of these k results exceeds 100 megabytes, the query will fail unless the query specifies cursor.allowDiskUse().如果在任何时候,这k个结果的内存占用超过100兆字节,则查询将失败,除非查询指定了cursor.allowDiskUse()

Interaction with Projection与投影的互动

When a set of results are both sorted and projected, the MongoDB query engine will always apply the sorting first.当一组结果同时进行排序和投影时,MongoDB查询引擎将始终首先应用排序。

Examples示例

A collection orders contain the following documents:集合orders包含以下文件:

db.orders.insertMany( [
{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 },
{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 },
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 },
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 },
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 },
{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }
] )

The following query, which returns all documents from the orders collection, does not specify a sort order:以下查询返回orders集合中的所有文档,但未指定排序顺序:

db.orders.find()

The query returns the documents in indeterminate order:查询以不确定的顺序返回文档:

{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }

The following query specifies a sort on the amount field in descending order.以下查询指定了amount字段的降序排序。

db.orders.find().sort( { amount: -1 } )

The query returns the following documents, in descending order of amount:查询按amount降序返回以下文档:

{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }
{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }

The following query specifies the sort order using the fields from an embedded document item. The query sorts first by the category field in ascending order, and then within each category, by the type field in ascending order.以下查询使用嵌入文档item中的字段指定排序顺序。查询首先按category字段升序排序,然后在每个category内按type字段升序排序。

db.orders.find().sort( { "item.category": 1, "item.type": 1 } )

The query returns the following documents, ordered first by the category field, and within each category, by the type field:查询返回以下文档,首先按category字段排序,然后在每个category中按type字段排序:

{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }

Return in Natural Order按自然顺序返回

The $natural parameter returns items according to their natural order within the database. $natural参数根据项目在数据库中的自然顺序返回项目。This ordering is an internal implementation feature, and you should not rely on any particular ordering of the documents.这种排序是一种内部实现功能,您不应该依赖于文档的任何特定排序。

Note

Prior to MongoDB 7.0, $natural accepts incorrect type values, such as 0, NaN, and -0.01. 在MongoDB 7.0之前,$natural接受不正确的类型值,如0NaN-0.01After MongoDB 7.0, if you pass any value other than 1 and -1 to $natural, MongoDB returns an error.在MongoDB 7.0之后,如果将1-1以外的任何值传递给$natural,MongoDB将返回错误。

Index Use索引使用

Queries that include a sort by $natural order do not use indexes to fulfill the query predicate with the following exception: If the query predicate is an equality condition on the _id field { _id: <value> }, then the query with the sort by $natural order can use the _id index.包含按$自然顺序排序的查询不使用索引来满足查询谓词,但以下情况除外:如果查询谓词是_id字段{ _id: <value> }上的相等条件,则按$自然次序排序的查询可以使用_id索引。