การจัดกลุ่มข้อมูลสินค้าและนับจำนวนรหัสสินค้าที่ซ้ำ
ใช้ $group ค่าฟิลด์หลายอย่างพร้อมกัน: $sum สำหรับผลรวมตัวเลข, $addToSet สำหรับเก็บค่าไม่ซ้ำ, $size นับจำนวน
ตัวอย่างข้อมูล
> db.demo466.insertOne({ "ProductPrice": 150, "ProductQuantity": 1, "ProductName": "Product-1", "ActualAmount": 110, "ProductProfit": 40, "ProductId": 1 });
> db.demo466.insertOne({ "ProductPrice": 150, "ProductQuantity": 1, "ProductName": "Product-1", "ActualAmount": 110, "ProductProfit": 40, "ProductId": 2 });
> db.demo466.insertOne({ "ProductPrice": 170, "ProductQuantity": 2, "ProductName": "Product-2", "ActualAmount": 130, "ProductProfit": 50, "ProductId": 3 });
Query Nested Group และ Sum
> db.demo466.aggregate([
{ $group: {
_id: { ProductName: "$ProductName" },
ActualAmount: { $sum: "$ActualAmount" },
ProductQuantity: { $sum: "$ProductQuantity" },
ProductId: { $addToSet: "$ProductId" }
}},
{ $project: {
ProductQuantity: true,
ActualAmount: true,
NumberOfProductInStock: { $size: "$ProductId" }
}}
]);
ผลลัพธ์
{ "_id": { "ProductName": "Product-2" }, "ActualAmount": 130, "ProductQuantity": 2, "NumberOfProductInStock": 1 }
{ "_id": { "ProductName": "Product-1" }, "ActualAmount": 220, "ProductQuantity": 2, "NumberOfProductInStock": 2 }
คำอธิบาย
- _id: { ProductName: "$ProductName" } - จัดกลุ่มตาม ProductName (เป็นออบเจ็กต์)
- $sum: "$ActualAmount" - รวม ActualAmount ในแต่ละกลุ่ม
- $sum: "$ProductQuantity" - รวม ProductQuantity ในแต่ละกลุ่ม
- $addToSet: "$ProductId" - เก็บ ProductId ที่ไม่ซ้ำกันเป็นอาร์เรย์
- $size: "$ProductId" - นับจำนวน ProductId ที่ไม่ซ้ำ (NumberOfProductInStock)
การขยาย: Nested $group (2 ระดับ)
db.demo466.aggregate([
{ $group: { _id: { ProductName: "$ProductName", ProductId: "$ProductId" }, ... } }, // ระดับ 1
{ $group: { _id: "$_id.ProductName", ProductIds: { $push: "$_id.ProductId" }, ... } } // ระดับ 2
]);