If the query bar displays the Sort option, you can specify the sort order of the returned documents.如果查询栏显示“排序”选项,则可以指定返回文档的排序顺序。
Note
If you specify a sort order in the Query Bar, the specified sort order overrides the default sort order you set in Settings.如果在查询栏中指定排序顺序,则指定的排序顺序将覆盖在“设置”中设置的默认排序顺序。
Compatibility兼容性
You can sort the returned documents for deployments hosted in the following environments:您可以对在以下环境中托管的部署的返回文档进行排序:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务 - 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的源代码可用、免费使用和自我管理版本
To learn more about sorting returned documents for deployments hosted in MongoDB Atlas, see Sort Query Results.要了解有关对MongoDB Atlas中托管的部署的返回文档进行排序的更多信息,请参阅排序查询结果。
Set the Sort Order设置排序顺序
To set the sort order:要设置排序顺序,请执行以下操作:
In the Query Bar, click Options.在查询栏中,单击“选项”。Enter the在“排序”字段中输入sortdocument into the Sort field.sort文档。To specify ascending order for a field, set the field to要指定字段的升序,请在排序文档中将字段设置为1in the sort document.1。To specify descending order for a field, set the field and要指定字段的降序,请在排序文档中设置字段和-1in the sort documents.-1。
Example示例The following以下sortdocument sorts results first byyearin descending order, and within each year, sort bynamein 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.键入时,“查找”按钮将被禁用,“排序”标签将变为红色,直到输入有效的查询。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.要清除查询栏和查询结果,请单击“重置”。
How Does the Compass Query Compare to MongoDB and SQL Queries?Compass查询与MongoDB和SQL查询相比如何?
$sort corresponds to the 对应于SQL ORDER BY ... clause in a SQL SELECT statement.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 }
Learn More了解更多
See the 请参阅MongoDB手册中的sort entry in the MongoDB Manual.sort条目。