Sử dụng $group và $sort trong cùng một pipeline Aggregation.
Tạo collection với document:
> db.sortAndGroupDemo.insertOne({ Price: 40, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e907") }
> db.sortAndGroupDemo.insertOne({ Price: 100, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e908") }
> db.sortAndGroupDemo.insertOne({ Price: 90, Product: 20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e909") }
> db.sortAndGroupDemo.insertOne({ Price: 200, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90a") }
> db.sortAndGroupDemo.insertOne({ Price: 70, Product: 20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90b") }
> db.sortAndGroupDemo.insertOne({ Price: 70, Product: 30 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bd78f00858fb12e90c") }
Hiển thị tất cả document:
> db.sortAndGroupDemo.find().pretty();
Kết quả:
{ "_id" : ObjectId("5ce8f2bc78f00858fb12e907"), "Price" : 40, "Product" : 10 }
{ "_id" : ObjectId("5ce8f2bc78f00858fb12e908"), "Price" : 100, "Product" : 10 }
{ "_id" : ObjectId("5ce8f2bc78f00858fb12e909"), "Price" : 90, "Product" : 20 }
{ "_id" : ObjectId("5ce8f2bc78f00858fb12e90a"), "Price" : 200, "Product" : 10 }
{ "_id" : ObjectId("5ce8f2bc78f00858fb12e90b"), "Price" : 70, "Product" : 20 }
{ "_id" : ObjectId("5ce8f2bd78f00858fb12e90c"), "Price" : 70, "Product" : 30 }
Truy vấn Aggregation: gom nhóm theo Product, sắp xếp theo Price tăng dần, chỉ hiển thị _id (Product):
> db.sortAndGroupDemo.aggregate(
[
{ "$group": { "_id": "$Product" }},
{ "$sort": { "Price": 1 }},
{ "$project": { "_id": 1 }}
]
);
Kết quả (Product unique, sắp xếp theo Price min của từng nhóm):
Lưu ý: $sort sau $group chỉ sắp xếp theo trường có trong _id hoặc dùng $first/$last trong $group để giữ giá trị Price.