MongoDB - 排序记录



本章我们将学习如何在 MongoDB 中排序记录。

sort() 方法

要在 MongoDB 中排序文档,需要使用sort() 方法。该方法接受一个包含字段列表及其排序顺序的文档。要指定排序顺序,使用 1 和 -1。1 用于升序,-1 用于降序。

语法

sort() 方法的基本语法如下:

>db.COLLECTION_NAME.find().sort({KEY:1})

示例

假设集合 myycol 包含以下数据。

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), 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() 方法将按升序显示文档。

广告
© . All rights reserved.