Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

MongoDB: หาจำนวนค่าซ้ำในเอกสารต่างๆ ด้วย Aggregation


นับความถี่ของค่า และจัดกลุ่ม "อื่นๆ" ด้วย 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 }

คำอธิบายขั้นตอน

  1. $group (1) - นับจำนวนต่อ StudentName
  2. $sort - เรียงมากไปน้อย
  3. $group (2) - รวมทุกกลุ่มเป็นอาร์เรย์ StudentName
  4. $project (1) - แยก first, second (Top 2) และ others (ที่เหลือ)
  5. $project (2) - สร้าง status array: Top 2 + "New Student Name" (รวม count ของ others)
  6. $unwind - แยก status กลับเป็นเอกสารแยกต่างหาก
  7. $project (3) - จัดรูปแบบ output ให้สะอาด

การประยุกต์

เหมาะสำหรับ: Top-N reports, "Others" category ใน dashboard, Pareto analysis, Data quality reports