Để tìm giá trị cao nhất từ các sub-array (mảng con) trong document MongoDB, bạn sử dụng Aggregation Framework với các stage: $project, $unwind, $sort, $limit.
Tạo dữ liệu mẫu
Mỗi document có mảng StudentDetails chứa nhiều object con với điểm Toán.
> db.findHighestValueDemo.insertOne( { _id: 10001, "StudentDetails": [ { "StudentName": "Chris", "StudentMathScore": 56}, { "StudentName": "Robert", "StudentMathScore":47 }, { "StudentName": "John", "StudentMathScore": 98 }] } );
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne( { _id: 10002, "StudentDetails": [ { "StudentName": "Ramit", "StudentMathScore": 89}, { "StudentName": "David", "StudentMathScore":76 }, { "StudentName": "Bob", "StudentMathScore": 97 } ] } );
{ "acknowledged" : true, "insertedId" : 10002 }
Hiển thị document:
> db.findHighestValueDemo.find().pretty();
Aggregation Pipeline tìm giá trị cao nhất
> db.findHighestValueDemo.aggregate([ {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}}, {$unwind:"$StudentDetails"}, {$sort:{"StudentDetails.StudentMathScore":-1}}, {$limit:1} ]).pretty();Kết quả:
Giải thích Pipeline
$project: Chỉ giữ các trường cần thiết$unwind: "Phẳng" mảng StudentDetails - mỗi element thành 1 document riêng$sort: Sắp xếp giảm dần theo StudentMathScore$limit: 1: Lấy document đầu tiên (điểm cao nhất)Lưu ý: Cách này trả về document gốc chứa element có giá trị cao nhất. Nếu chỉ cần giá trị max, dùng
$maxtrong$group.