集册 Mongodb 教程 记录排序

记录排序

黑派客     最近更新时间:2020-08-04 05:37:59

411

sort() 方法

MongoDB 中的文档排序是通过 sort() 方法来实现的。sort() 方法可以通过一些参数来指定要进行排序的字段,并使用 1 和 -1 来指定排序方式,其中 1 表示升序,而 -1 表示降序。

格式

sort() 方法基本格式为:

>db.COLLECTION_NAME.find().sort({KEY:1})

范例

假设集合 myycol 包含下列数据:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}  

下面的范例将显示按照降序排列标题的文档。

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

注意,如果不指定排序规则,sort() 方法将按照升序排列显示文档。