Sort the Returned Documents对返回的文档进行排序

If the query bar displays the Sort option, you can specify the sort order of the returned documents.如果查询栏显示“排序”选项,则可以指定返回文档的排序顺序。

To set the sort order:要设置排序顺序,请执行以下操作:

  1. In the Query Bar, click Options.在查询栏中,单击“选项”。
  2. Enter the sort document into the Sort field.在“排序”字段中输入sort文档。

    • To specify ascending order for a field, set the field to 1 in the sort document.要为字段指定升序,请在排序文档中将字段设置为1
    • To specify descending order for a field, set the field and -1 in the sort documents.要为字段指定降序,请在排序文档中设置字段和-1
    Example

    The following sort document sorts results first by year in descending order, and within each year, sort by name in ascending order.下面的sort文档首先按year降序对结果进行排序,然后在每年内按name升序对结果进行排序。

    { year: -1, name: 1 }

    As you type, the Find button is disabled and the Sort label turns red until a valid query is entered.键入时,“查找”按钮将被禁用,“排序”标签将变为红色,直到输入有效的查询。

  3. Click Find to run the query and view the updated results.单击“查找”以运行查询并查看更新的结果。

To clear the query bar and the results of the query, click Reset.要清除查询栏和查询结果,请单击“重置”。

See the sort entry in the MongoDB Manual.请参阅MongoDB手册中的sort条目。

$sort corresponds to the ORDER BY ... clause in a SQL SELECT statement.$sort对应于SQL SELECT语句中的ORDER BY ...子句。

Example

You have 3,235 articles. You would like to see a list of articles sorted alphabetically by headline.你有3235篇文章。您希望看到按标题字母顺序排列的文章列表。

SQL
SELECT * FROM article
ORDER BY headline ASC;
MongoDB AggregationMongoDB聚合
db.article.aggregate(
  { $sort : { headline : 1 } }
);
Compass Sort OptionCompass排序选项
$sort : { headline : 1 }