Sử dụng aggregation với $unwind (phân tách mảng) và $sort để sắp xếp tài liệu theo giá trị bên trong mảng. Tạo collection:
> db.demo577.insertOne({
... "student": {
... "details": [
... { Name:"Chris", Score:45 },
... { Name:"Bob", Score:33 },
... { Name:"David", Score:48 }
... ]
... }
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e916ff1581e9acd78b427ff") }
Hiển thị dữ liệu:
> db.demo577.find();
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : [ { "Name" : "Chris", "Score" : 45 }, { "Name" : "Bob", "Score" : 33 }, { "Name" : "David", "Score" : 48 } ] } }
Pipeline: Unwind mảng student, unwind mảng details, sắp xếp theo Score giảm dần:
> db.demo577.aggregate([
... {$unwind:"$student"},
... {$unwind:"$student.details"},
... {$sort:{"student.details.Score":-1}}
... ]);
Kết quả (David 48 → Chris 45 → Bob 33):
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "David", "Score" : 48 } } }
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Chris", "Score" : 45 } } }
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Bob", "Score" : 33 } } }
Lưu ý: Sau $unwind, mỗi phần tử mảng thành tài liệu riêng biệt. Kết quả không còn cấu trúc mảng gốc. Để gom lại, dùng $group + $push.