Để sắp xếp các tài liệu con bên trong mảng, cần sử dụng pipeline aggregation với $unwind, $sort, sau đó $group để tái cấu trúc mảng.
Tạo collection:
> db.demo23.insertOne({
"StudentDetails" : [
{ "Name" : "David", "Age" : 23 },
{ "Name" : "Adam", "Age" : 24 }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14c3eb22d07d3b95082e71") }
Xem dữ liệu ban đầu (mảng chưa sắp xếp):
> db.demo23.find().pretty()
{
"_id" : ObjectId("5e14c3eb22d07d3b95082e71"),
"StudentDetails" : [
{ "Name" : "David", "Age" : 23 },
{ "Name" : "Adam", "Age" : 24 }
]
}
Pipeline aggregation để sắp xếp mảng con theo Name tăng dần:
> db.demo23.aggregate([
{ "$unwind" : "$StudentDetails" },
{ "$sort" : { "StudentDetails.Name" : 1 }},
{ "$match" : { }},
{ "$group" : { "StudentDetails" : { "$push" : { "Name" : "$StudentDetails.Name" }}, "_id" : null }},
{ "$project" : { "_id" : 0, "StudentDetails" : 1 }}
]);
Kết quả mảng đã sắp xếp:
{ "StudentDetails" : [ { "Name" : "Adam" }, { "Name" : "David" } ] }
Các bước:
$unwind: Phân tách mảng thành các tài liệu riêng lẻ$sort: Sắp xếp theo trường mong muốn$groupvới$push: Gom lại thành mảng theo thứ tự đã sắp xếp$project: Định dạng đầu ra
Lưu ý: Từ MongoDB 3.6+, có thể dùng $sortArray (trong $project) để sắp xếp mảng trực tiếp mà không cần unwind.