MongoDB 排序记录
MongoDB 排序记录
在本章中,我们将学习如何在MongoDB中对记录进行排序
sort()方法
若要在MongoDB中排序文档,需要使用sort()方法。sort方法接受包含字段列表及其排序顺序。排序顺序可以指定为1或-1:1用于升序,-1用于降序。
语法
>db.COLLECTION_NAME.find().sort({KEY:1})
例子
假设myycol集合有如下数据:
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
下面的示例将按标题降序显示文档。
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} >
请注意,如果不指定排序首选项,sort()方法将按升序显示文档。