mongodb 聚合中排序_在MongoDB中排序

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命令。

List down collection data in MongoDB

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

Now run the below query to sort the data by the name field in descending order :

现在运行以下查询以按名称字段降序对数据进行排序:

db.student.find().sort({name : -1})
List down collection data in MongoDB

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 聚合中排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值