MongoDB 排序
MongoDB 排序
MongoDB sort() 方法
在 MongoDB 中使用 sort() 方法對資料進行排序,sort() 方法可以通過引數指定排序的欄位,並使用 1 和 -1 來指定排序的方式,其中 1 為升序排列,而 -1 是用於降序排列。
語法
sort()方法基本語法如下所示:
>db.COLLECTION_NAME.find().sort({KEY:1})
例項
col 集合中的資料如下:
{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一種建立動態互動性站點的強有力的伺服器端指令碼語言。", "by" : "入門教學", "url" : "http://www.itread01.com", "tags" : [ "php" ], "likes" : 200 } { "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司於1995年5月推出的高階程式設計語言。", "by" : "入門教學", "url" : "http://www.itread01.com", "tags" : [ "java" ], "likes" : 150 } { "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一個 Nosql 資料庫", "by" : "入門教學", "url" : "http://www.itread01.com", "tags" : [ "mongodb" ], "likes" : 100 }
以下例項演示了 col 集合中的資料按欄位 likes 的降序排列:
>db.col.find({},{"title":1,_id:0}).sort({"likes":-1}) { "title" : "PHP 教程" } { "title" : "Java 教程" } { "title" : "MongoDB 教程" } >