MongoDB排序:sort()方法
11个月前 (04-28)
要在 MongoDB 中对查询到的文档进行排序,您可以使用 sort() 方法,该方法的语法格式如下:
【示例】假设“course”中有如下数据:
db.collection_name.find().sort({key:1})
其中 key 用来定义要根据那个字段进行排序,后面的值 1 则表示以升序进行排序,若要以降序进行排序则需要将其设置为 -1。【示例】假设“course”中有如下数据:
注意,如果在使用 sort() 方法时未指定排序的选项,那么 sort() 方法将默认按 _id 的升序显示文档,如下所示:> db.course.find()
{ "_id" : ObjectId("60331a7eee79704753940391"), "title" : "HTML教程", "author" : "编程帮", "url" : "http://www.bianchen网站站点" rel="nofollow" />
> db.course.find({}, {"title":1,_id:0}).sort({"title":-1})
{ "title" : "MongoDB教程" }
{ "title" : "HTML教程" }
{ "title" : "C#教程" }
> db.course.find({}, {"title":1,_id:0}).sort({})
{ "title" : "HTML教程" }
{ "title" : "C#教程" }
{ "title" : "MongoDB教程" }