MongoDB 聚合排序

Mehvish Ashiq 2022年6月7日
MongoDB 聚合排序

要使用 MongoDB 进行聚合操作,需要对聚合管道阶段有足够的了解。本教程将通过一个示例来探索 $sort 阶段以执行 MongoDB 聚合排序。

MongoDB 聚合排序

让我们有一个场景来练习代码示例。我们有一个名为 student 的集合,其中包含基本信息。

你还可以使用以下查询与我们在同一页面上。

示例代码:

> db.createCollection('student');
> db.student.insertMany([
    {"student_code": "ma001", "name": "Mehvish Ashiq", "postcode": 2000},
    {"student_code": "tc002", "name": "Thomas Christopher", "postcode": 2001},
    {"student_code": "km003", "name": "Krishna Mehta", "postcode": 2000},
    {"student_code": "ar004", "name": "Aftab Raza", "postcode": 2000},
    {"student_code": "za005", "name": "Zeenat Ashraf", "postcode": 2002},
    {"student_code": "ka006", "name": "Kanwal Ali", "postcode": 2002}
]);
> db.student.find().pretty();

输出:

{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e97b"),
        "student_code" : "ma001",
        "name" : "Mehvish Ashiq",
        "postcode" : 2000
}
{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e97c"),
        "student_code" : "tc002",
        "name" : "Thomas Christopher",
        "postcode" : 2001
}
{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e97d"),
        "student_code" : "km003",
        "name" : "Krishna Mehta",
        "postcode" : 2000
}
{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e97e"),
        "student_code" : "ar004",
        "name" : "Aftab Raza",
        "postcode" : 2000
}
{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e97f"),
        "student_code" : "za005",
        "name" : "Zeenat Ashraf",
        "postcode" : 2002
}
{
        "_id" : ObjectId("629afe5a0a3b0e96fe92e980"),
        "student_code" : "ka006",
        "name" : "Kanwal Ali",
        "postcode" : 2002
}

接下来,我们要确定容纳最多学生但以排序形式存在的 postcode。为此,请检查以下示例代码。

示例代码:

> db.student.aggregate([
    { $group: { _id: '$postcode', students: { $sum: 1 } } },
    { $sort: {_id: 1} }
]);

输出:

{ "_id" : 2000, "students" : 3 }
{ "_id" : 2001, "students" : 1 }
{ "_id" : 2002, "students" : 2 }

在这里,我们使用 aggregate() 函数计算指定集合或视图中数据的聚合值。在 aggregate() 方法中,我们根据 postcode 字段对文档进行分组。

此外,我们将 postcode 返回为 _id,学生将每个 postcode 计为 students。在这里,我们使用 $sum 来获取每个 postcode 的学生人数。

$sum 通过忽略非数值来计算并返回数值的总和。

最后,我们使用 $sort 阶段根据项目需要以升序或降序对它们进行排序。1 用于升序,而 -1 用于降序。

作者: Mehvish Ashiq
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook