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

MongoDB: นับ Unique Fields จำแนกตาม Field อื่นด้วย Aggregate

ใช้ aggregation pipeline 2 ระดับ $group เพื่อนับค่า unique ของ Name2 จำแนกตาม Name1 สร้างคอลเลกชันตัวอย่าง:

> db.demo354.insertOne({"Name1":"Chris","Name2":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5685a6f8647eb59e5620c0") }
> db.demo354.insertOne({"Name1":"Chris","Name2":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5685a9f8647eb59e5620c1") }
> db.demo354.insertOne({"Name1":"Chris","Name2":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5685aff8647eb59e5620c2") }
> db.demo354.insertOne({"Name1":"Carol","Name2":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5685c4f8647eb59e5620c3") }
> db.demo354.insertOne({"Name1":"Carol","Name2":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5685c5f8647eb59e5620c4") }

แสดงข้อมูล:

> db.demo354.find();

คิวรีนับ unique Name2 ต่อ Name1:

> db.demo354.aggregate([
  { $group: { _id: { "Name1": "$Name1", "Name2": "$Name2" } } },
  { $group: { _id: "$_id.Name1", "Name2": { $sum: 1 } } },
  { $project: { _id: 0, Name1: "$_id", Name2: 1 } }
])

ผลลัพธ์ (Chris มี Name2 unique 2 ค่า: David, Bob | Carol มี 1 ค่า: John):

{ "Name2" : 2, "Name1" : "Chris" }
{ "Name2" : 1, "Name1" : "Carol" }

คำอธิบาย Pipeline

  1. $group แรก: จัดกลุ่มตามคู่ (Name1, Name2) → ได้ distinct pairs
  2. $group ที่สอง: จัดกลุ่มตาม Name1 นับจำนวนคู่ด้วย $sum: 1
  3. $project: จัดรูปแบบ output ให้อ่านง่าย

วิธีอื่น (MongoDB 4.4+)

ใช้ $setUnion หรือ $addToSet ใน $group เดียว:

{ $group: { _id: "$Name1", uniqueName2: { $addToSet: "$Name2" } } }
{ $project: { Name1: "$_id", Name2Count: { $size: "$uniqueName2" } } }