mongodb 聚合中排序
Sorting the data in any database is one of the vital operations in any database management system. MongoDB provides sort()
function in order to sort the data in a collection. Sort function in MongoDB accepts a list of values and an integer value 1 or -1 which states whether the collection to be sorted in ascending (1) or descending (-1) order.
对任何数据库中的数据进行排序是任何数据库管理系统中至关重要的操作之一。 MongoDB提供sort()
函数以便对集合中的数据进行排序。 MongoDB中的Sort函数接受值列表和1或-1的整数,该整数表示要对集合进行升序(1)还是降序(-1)排序。
Syntax for sort function:
排序功能的语法:
db.collection_name.find().sort({KEY : 1})
Consider a collection named student containing 3 records. Let us now see how the data can be sorted using the sort()
function in MongoDB.
考虑一个名为student的集合,其中包含3条记录。 现在让我们看看如何使用MongoDB中的sort()
函数对数据进行排序。
To list down all the data in a collection, use the find()
command. To create the same sample data as used here in the example, create a collection named student
and insert 3 documents with one field name and some value for it. In the next step we will run the sort command on this sample data.
要列出集合中的所有数据,请使用find()
命令。 要创建与示例中使用的示例数据相同的示例数据,请创建一个名为student
的集合,并插入3个文档,其中包含一个字段名和一些值。 在下一步中,我们将对该示例数据运行sort命令。
Now run the below query to sort the data by the name field in ascending order :
现在运行以下查询以按名称字段升序对数据进行排序:
db.student.find().sort({name : 1})
![List down collection data in MongoDB](https://www.studytonight.com/mongodb/images/sorting-in-mongodb-2.png)
Now run the below query to sort the data by the name field in descending order :
现在运行以下查询以按名称字段降序对数据进行排序:
db.student.find().sort({name : -1})
NOTE: If you do not specify the sorting preference(i.e 1 or -1), then by default documents in a collection are sorted in ascending order.
注意:如果未指定排序首选项(即1或-1),则默认情况下,集合中的文档按升序排序。
翻译自: https://www.studytonight.com/mongodb/sorting-in-mongodb
mongodb 聚合中排序