Để sắp xếp mảng lồng nhau trong MongoDB, sử dụng $sort trong aggregation pipeline. Tạo collection:
> db.demo505.insertOne({
"details": [
{ Name: "Chris", "Score": 58 },
{ Name: "Bob", "Score": 45 },
{ Name: "John", "Score": 68 },
{ Name: "David", "Score": 46 }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e882a6b987b6e0e9d18f574") }
Hiển thị dữ liệu gốc (chưa sắp xếp):
> db.demo505.find();
Kết quả:
Pipeline:
$unwindphân tách mảng,$sortsắp xếp theo Score tăng dần,$groupgom lại thành mảng:> db.demo505.aggregate([ { $unwind: "$details" }, { $sort: { "details.Score": 1 } }, { $group: { _id: "$_id", details: { $push: "$details" } } } ]);Kết quả mảng details đã được sắp xếp theo Score tăng dần:
Lưu ý: Phương pháp này tạo bản sao tài liệu với mảng đã sắp xếp, không thay đổi dữ liệu gốc. Để cập nhật vĩnh viễn, dùng
$outhoặc update sau aggregation.