Docs HomeMongoDB Compass

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

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

Set the Sort Order设置排序顺序

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.单击“查找”运行查询并查看更新的结果。

Clear the Query清除查询

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

To Learn More了解更多信息

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

How Does the Compass Query Compare to MongoDB and SQL Queries?Compass查询与MongoDB和SQL查询相比如何?

$sort corresponds to the ORDER BY ... clause in a SQL SELECT statement.对应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 Aggregation
db.article.aggregate(

{ $sort : { headline : 1 } }

);
Compass Sort OptionCompass排序选项
$sort : { headline : 1 }