在MongoDB中使用使用?sort()
?方法對數(shù)據(jù)進行排序,?sort()
?方法可以通過參數(shù)指定排序的字段,并使用 1 和 -1 來指定排序的方式,其中 1 為升序排列,而-1是用于降序排列。
?sort()
?方法基本語法如下所示:
>db.COLLECTION_NAME.find().sort({KEY:1})
col 集合中的數(shù)據(jù)如下:
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
以下實例演示了 col 集合中的數(shù)據(jù)按字段 title 的降序排列:
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} >
注: 如果沒有指定?
sort()
?方法的排序方式,默認(rèn)按照文檔的升序排列。
更多建議: