Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Thực hiện Aggregation Sort (sắp xếp) trong MongoDB

Sử dụng aggregate() kết hợp stage $sort để sắp xếp kết quả aggregation pipeline. Thường dùng sau $group để sắp xếp các nhóm.

Cú pháp

db.collection.aggregate([
    { $group: { _id: "$trườngNhóm", "tênTrườngTính": { $sum: 1 } } },
    { $sort: { "_id": 1 } }  // 1: tăng dần, -1: giảm dần
]).pretty();

Ví dụ minh họa

Tạo collection aggregationSortDemo với dữ liệu có StudentId trùng lặp:

> db.aggregationSortDemo.insertOne({"StudentId": 98, "StudentFirstName": "John", "StudentLastName": "Smith"});
> db.aggregationSortDemo.insertOne({"StudentId": 128, "StudentFirstName": "Carol", "StudentLastName": "Taylor"});
> db.aggregationSortDemo.insertOne({"StudentId": 110, "StudentFirstName": "David", "StudentLastName": "Miller"});
> db.aggregationSortDemo.insertOne({"StudentId": 139, "StudentFirstName": "Chris", "StudentLastName": "Brown"});
> db.aggregationSortDemo.insertOne({"StudentId": 125, "StudentFirstName": "Sam", "StudentLastName": "Williams"});
> db.aggregationSortDemo.insertOne({"StudentId": 139, "StudentFirstName": "Mike", "StudentLastName": "Wilson"});

Hiển thị tất cả:

> db.aggregationSortDemo.find().pretty();

Case 1: Sắp xếp giảm dần (Descending) theo StudentId

> db.aggregationSortDemo.aggregate([
    { $group: { _id: "$StudentId", "TotalOccurrences": { $sum: 1 } } },
    { $sort: { _id: -1 } }
]).pretty();

Kết quả:

{ "_id" : 139, "TotalOccurrences" : 2 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 98, "TotalOccurrences" : 1 }

Case 2: Sắp xếp tăng dần (Ascending) theo StudentId

> db.aggregationSortDemo.aggregate([
    { $group: { _id: "$StudentId", "TotalOccurrences": { $sum: 1 } } },
    { $sort: { _id: 1 } }
]).pretty();

Kết quả:

{ "_id" : 98, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 139, "TotalOccurrences" : 2 }

Sắp xếp theo trường tính toán (computed field)

// Sắp xếp theo TotalOccurrences giảm dần
db.aggregationSortDemo.aggregate([
    { $group: { _id: "$StudentId", "TotalOccurrences": { $sum: 1 } } },
    { $sort: { "TotalOccurrences": -1, "_id": 1 } }  // Ưu tiên count cao, sau đó ID tăng
]).pretty();

Lưu ý hiệu suất

  • Đặt $sort ngay sau $match hoặc ở đầu pipeline để tận dụng index (nếu có).
  • Nếu bộ nhớ vượt quá 100MB, thêm { allowDiskUse: true } vào aggregate.
  • Sử dụng $sort trước $limit để lấy Top-N hiệu quả (MongoDB tự tối ưu).