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

Sắp xếp theo thứ tự từ khóa (custom sort) trong MongoDB

MongoDB sắp xếp mặc định theo thứ tự ASCII (số, hoa, thường). Để sắp xếp theo **thứ tự tùy chỉnh** (ví dụ: MongoDB -> MySQL -> Java), bạn dùng Aggregation Pipeline: tạo trường ảo sortByWords gán số thứ tự cho từng giá trị, rồi $sort theo trường đó.

1. Tạo bộ sưu tập

> db.demo62.insertOne({ "Subject": "MySQL" });
> db.demo62.insertOne({ "Subject": "MongoDB" });
> db.demo62.insertOne({ "Subject": "Java" });

2. Xem dữ liệu (mặc định sort theo _id)

> db.demo62.find();

3. Aggregation: Tạo trọng số sắp xếp tùy chỉnh

> db.demo62.aggregate([
    {
        $addFields: {
            sortByWords: {
                $cond: [
                    { $eq: ["$Subject", "MongoDB"] }, 0,  // Ưu tiên 1: MongoDB = 0
                    { $cond: [{ $eq: ["$Subject", "MySQL"] }, 1, 2] } // Ưu tiên 2: MySQL = 1, còn lại = 2
                ]
            }
        }
    },
    { $sort: { sortByWords: 1 } }
]);

4. Kết quả

{ "_id": ObjectId("..."), "Subject": "MongoDB", "sortByWords": 0 }
{ "_id": ObjectId("..."), "Subject": "MySQL", "sortByWords": 1 }
{ "_id": ObjectId("..."), "Subject": "Java", "sortByWords": 2 }

Cách mở rộng (dễ bảo trì hơn): Dùng $switch (MongoDB 3.4+):

$addFields: {
    sortByWords: {
        $switch: {
            branches: [
                { case: { $eq: ["$Subject", "MongoDB"] }, then: 0 },
                { case: { $eq: ["$Subject", "MySQL"] }, then: 1 }
            ],
            default: 2
        }
    }
}

Ứng dụng: Sắp xếp trạng thái (Pending -> Processing -> Done), mức độ ưu tiên (High -> Medium -> Low), enum bất kỳ.