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 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