ใช้ $setIntersection ใน Aggregation หาค่าที่ซ้ำกันระหว่างอาร์เรย์
โอเปอเรเตอร์ $setIntersection รับอาร์เรย์ 2 ตัวขึ้นไป คืนค่าอาร์เรย์ที่มีเฉพาะค่าที่ปรากฏใน ทุกอาร์เรย์ (Intersection)
ตัวอย่างข้อมูล: 3 เอกสาร มีอาร์เรย์ต่างกัน
> db.setInterSectionDemo.insertOne({"_id":101, "Value1":[55,67,89]});
> db.setInterSectionDemo.insertOne({"_id":102, "Value2":[90,45,55]});
> db.setInterSectionDemo.insertOne({"_id":103, "Value3":[92,67,45]});
Pipeline: หาส่วนร่วมระหว่าง Value1 (_id=101) และ Value3 (_id=103)
> db.setInterSectionDemo.aggregate([
{ $match: { "_id": { $in: [101, 103] } } },
{ $group: {
_id: 0,
firstValue: { $first: "$Value1" },
secondValue: { $last: "$Value3" }
}},
{ $project: {
firstValue: 1,
secondValue: 1,
CommonValue: { $setIntersection: ["$firstValue", "$secondValue"] },
_id: 0
}}
]);
ผลลัพธ์
{ "firstValue" : [ 55, 67, 89 ], "secondValue" : [ 92, 67, 45 ], "CommonValue" : [ 67 ] }
คำอธิบาย
- Value1: [55, 67, 89]
- Value3: [92, 67, 45]
- Intersection: [67] (ค่าที่อยู่ในทั้งคู่)
Set Operators อื่นๆ ใน Aggregation
| Operator | ความหมาย | ตัวอย่าง |
|---|---|---|
$setUnion | รวมทั้งหมด (Unique) | [1,2] ∪ [2,3] = [1,2,3] |
$setIntersection | ส่วนร่วม | [1,2] ∩ [2,3] = [2] |
$setDifference | ต่างกัน (A - B) | [1,2] - [2,3] = [1] |
$setIsSubset | Subset หรือไม่ (Boolean) | [1,2] ⊆ [1,2,3] = true |
$setEquals | เท่ากันหมด (Boolean) | [1,2] = [2,1] = true |
ข้อจำกัด
- ทำงานกับ Array ของ Primitive Values (String, Number, Boolean)
- ไม่ทำงานกับ Array ของ Objects โดยตรง (ต้อง Normalize ก่อน)
- ผลลัพธ์ Unique และ Sorted อัตโนมัติ