Sử dụng $sort trong MongoDB aggregation để sắp xếp tài liệu. Tạo collection với mảng lồng nhau:
> db.demo652.insertOne({
value: 10,
"details": [
{ "ProductName": "Product-1", "ProductQuantity": 8, "ProductPrice": 500 },
{ "ProductName": "Product-2", "ProductQuantity": 7, "ProductPrice": 500 }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62") }
> db.demo652.insertOne({
value: 5,
"details": [
{ "ProductName": "Product-1", "ProductQuantity": 8, "ProductPrice": 500 },
{ "ProductName": "Product-2", "ProductQuantity": 7, "ProductPrice": 500 }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63") }
Hiển thị dữ liệu:
> db.demo652.find();
Kết quả (value 10 trước, 5 sau):
Pipeline phức tạp:
$unwinddetails,$match(rỗng),$groupgom lại theo _id lấy value đầu tiên làm ProductPrice, push ProductName,$sorttheo ProductPrice tăng dần (1),$projectchọn trường output:> db.demo652.aggregate([ { "$unwind": "$details" }, { "$match": {} }, { "$group": { "ProductPrice": { "$first": "$value" }, "details": { "$push": { "ProductName": "$details.ProductName" } }, "_id": "$_id" }}, { "$sort": { "ProductPrice": 1 } }, { "$project": { "_id": 0, "ProductPrice": 1, "details": 1 } } ]).pretty()Kết quả sắp xếp tăng dần theo ProductPrice (5 trước, 10 sau):
Lưu ý: Pipeline này phức tạp hơn cần thiết cho ví dụ đơn giản. Thông thường chỉ cần
db.demo652.find().sort({value: 1})để sắp xếp tài liệu gốc.