On this page本页内容
$orderby
¶Deprecated since v3.2从v3.2开始就不推荐了。
Starting in v3.2, the 从v3.2开始$orderby
operator is deprecated in the mongo
shell. $orderby
运算符在mongo
shell中不受欢迎。In the 在mongo
shell, use cursor.sort()
instead.mongo
shell中,请改用cursor.sort()
。
The $orderby
operator sorts the results of a query in ascending or descending order.$orderby
运算符按升序或降序对查询结果进行排序。
The mongo
shell provides the cursor.sort()
method:mongo
shell提供了cursor.sort()
方法:
You can also specify the option in either of the following forms:您还可以通过以下任一形式指定该选项:
These examples return all documents in the collection named 这些示例返回名为collection
sorted by the age
field in descending order. collection
的集合中按age
字段降序排序的所有文档。Specify a value to 为$orderby
of negative one (e.g. -1
, as above) to sort in descending order or a positive value (e.g. 1
) to sort in ascending order.$orderby
指定一个负值(如-1
,如上所述)以按降序排序,或指定一个正值(如-1
)以按升序排序。
Since indexes contain ordered records, MongoDB can obtain the results of a sort from an index which includes the sort fields. 由于索引包含有序记录,MongoDB可以从包含排序字段的索引中获取排序结果。MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.如果排序使用与查询谓词相同的索引,MongoDB可以使用多个索引来支持排序操作。
If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data. 如果MongoDB无法使用一个或多个索引来获取排序顺序,MongoDB必须对数据执行阻塞排序操作。A blocking sort indicates that MongoDB must consume and process all input documents to the sort before returning results. 阻塞排序表示MongoDB必须在返回结果之前使用并处理所有输入文档。Blocking sorts do not block concurrent operations on the collection or database.阻止排序不会阻止集合或数据库上的并发操作。
Sort operations that use an index often have better performance than blocking sorts. 使用索引的排序操作通常比阻塞排序具有更好的性能。For more information on creating indexes to support sort operations, see Use Indexes to Sort Query Results.有关创建索引以支持排序操作的更多信息,请参阅使用索引对查询结果进行排序。
If MongoDB requires using more than 100 megabytes of system memory for the blocking sort operation, MongoDB returns an error unless the query specifies 如果MongoDB需要使用超过100 MB的系统内存来执行阻塞排序操作,MongoDB将返回一个错误,除非查询指定cursor.allowDiskUse()
(New in MongoDB 4.4). cursor.allowDiskUse()
(MongoDB 4.4中新增)。allowDiskUse()
allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.允许MongoDB在处理阻塞排序操作时,使用磁盘上的临时文件存储超过100 MB系统内存限制的数据。
To avoid this error, create an index to support the sort operation or use 要避免此错误,请创建一个支持排序操作的索引,或将$orderby
in conjunction with cursor.maxTimeMS()
and/or cursor.limit()
. $orderby
与cursor.maxTimeMS()
和/或cursor.limit()
结合使用。The cursor.limit()
increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm. cursor.limit()
通过优化算法提高速度并减少返回此查询所需的内存量。The specified limit must result in a number of documents that fall within the 100 megabyte limit.指定的限制必须导致大量文档在100 MB的限制范围内。