MongoDB排序:sort()方法

 
要在 MongoDB 中对查询到的文档进行排序,您可以使用 sort() 方法,该方法的语法格式如下:

db.collection_name.find().sort({key:1})

其中 key 用来定义要根据那个字段进行排序,后面的值 1 则表示以升序进行排序,若要以降序进行排序则需要将其设置为 -1。

【示例】假设集合“course”中有如下数据:
> db.course.find()
{ "_id" : ObjectId("60331a7eee79704753940391"), "title" : "HTML教程", "author" : "编程帮", "url" : "http://www.biancheng.com/html/index.html" }
{ "_id" : ObjectId("60331a7eee79704753940392"), "title" : "C#教程", "author" : "编程帮", "url" : "http://www.biancheng.com/csharp/index.html" }
{ "_id" : ObjectId("60331a7eee79704753940393"), "title" : "MongoDB教程", "author" : "编程帮", "url" : "http://www.biancheng.com/mongodb/index.html" }
若要将集合中的数据按照 title 字段降序排列,示例代码如下:
> db.course.find({}, {"title":1,_id:0}).sort({"title":-1})
{ "title" : "MongoDB教程" }
{ "title" : "HTML教程" }
{ "title" : "C#教程" }
注意,如果在使用 sort() 方法时未指定排序的选项,那么 sort() 方法将默认按 _id 的升序显示文档,如下所示:
> db.course.find({}, {"title":1,_id:0}).sort({})
{ "title" : "HTML教程" }
{ "title" : "C#教程" }
{ "title" : "MongoDB教程" }