นับความถี่ของค่า และจัดกลุ่ม "อื่นๆ" ด้วย Pipeline หลายขั้นตอน
ใช้ $group นับจำนวน, $sort เรียง, แล้ว $project แยก Top-N และรวมที่เหลือเป็น "New Student Name"
ตัวอย่างข้อมูล
> db.demo452.insertOne({ "StudentName": "John", "StudentAge": 21 });
> db.demo452.insertOne({ "StudentName": "John", "StudentAge": 22 });
> db.demo452.insertOne({ "StudentName": "John", "StudentAge": 23 });
> db.demo452.insertOne({ "StudentName": "David", "StudentAge": 24 });
> db.demo452.insertOne({ "StudentName": "David", "StudentAge": 25 });
Query Aggregation สมบูรณ์
> db.demo452.aggregate([
{ $group: { _id: "$StudentName", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $group: { _id: 1, StudentName: { $push: { StudentName: "$_id", count: "$count" } } } },
{ $project: {
first: { $arrayElemAt: ["$StudentName", 0] },
second: { $arrayElemAt: ["$StudentName", 1] },
others: { $slice: ["$StudentName", 2, { $size: "$StudentName" }] }
}},
{ $project: {
status: [
"$first", "$second",
{ StudentName: "New Student Name", count: { $sum: "$others.count" } }
]
}},
{ $unwind: "$status" },
{ $project: { _id: 0, StudentName: "$status.StudentName", count: "$status.count" } }
]);
ผลลัพธ์
{ "StudentName": "John", "count": 3 }
{ "StudentName": "David", "count": 2 }
{ "StudentName": "New Student Name", "count": 0 }
คำอธิบายขั้นตอน
- $group (1) - นับจำนวนต่อ StudentName
- $sort - เรียงมากไปน้อย
- $group (2) - รวมทุกกลุ่มเป็นอาร์เรย์ StudentName
- $project (1) - แยก first, second (Top 2) และ others (ที่เหลือ)
- $project (2) - สร้าง status array: Top 2 + "New Student Name" (รวม count ของ others)
- $unwind - แยก status กลับเป็นเอกสารแยกต่างหาก
- $project (3) - จัดรูปแบบ output ให้สะอาด
การประยุกต์
เหมาะสำหรับ: Top-N reports, "Others" category ใน dashboard, Pareto analysis, Data quality reports