Latest web development tutorials

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.w3big.com", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "本教程", "url" : "http://www.w3big.com", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "本教程", "url" : "http://www.w3big.com", "tags" : [ "mongodb" ], "likes" : 100 }

以下實例演示了col 集合中的數據按字段likes 的降序排列:

>db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
{ "title" : "PHP 教程" }
{ "title" : "Java 教程" }
{ "title" : "MongoDB 教程" }
>

注:如果沒有指定sort()方法的排序方式,默認按照文檔的升序排列。