Mongodb 简明教程

MongoDB - Sort Records

在本章中,我们将学习如何对 MongoDB 中的记录进行排序。

The sort() Method

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

Syntax

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

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

Example

考虑集合 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() 方法将按升序显示文档。