Sử dụng aggregation nhiều $unwind để flatten mảng lồng sâu, sau đó sort và limit. Tạo collection phức tạp:
> db.demo70.insertOne({
"first": [
{ "details": { "second": [ {"StudentDetails":{"Score":10}}, {"StudentDetails":{"Score":20}}, {"StudentDetails":{"Score":30}} ] } },
{ "details": { "second": [ {"StudentDetails":{"Score":11}}, {"StudentDetails":{"Score":18}}, {"StudentDetails":{"Score":29}} ] } }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29ad4d0912fae76b13d76d") }
Hiển thị cấu trúc sâu 4 cấp:
> db.demo70.find().pretty();
Aggregation: unwind first -> unwind second -> sort Score giảm -> limit 3 -> replaceRoot -> sort tăng:
> db.demo70.aggregate([
{ $unwind: "$first" },
{ $unwind: "$first.details.second" },
{ $sort: { "first.details.second.StudentDetails.Score": -1 } },
{ $limit: 3 },
{ $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
{ $sort: { "Score": 1 } }
]);
Kết quả - top 3 Score cao nhất (30, 29, 20) sắp tăng dần:
Quy trình: 1) Unwind mảng first, 2) Unwind mảng second, 3) Sort giảm theo Score, 4) Limit 3 lấy top 3, 5) ReplaceRoot đưa StudentDetails lên root, 6) Sort tăng để hiển thị 20, 29, 30.