ใช้ Operator $setIntersection ใน Aggregation Pipeline เพื่อคืนค่าเฉพาะ Element ที่ปรากฏใน ทั้งสองอาร์เรย์ (Set Intersection) ทำงานคล้ายการหาส่วนร่วมของเซต
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.filterArrayElementsDemo.insertOne({"Scores": [10,45,67,78,90,98,99,92]});
{ "acknowledged": true, "insertedId": ObjectId("5cd2d582b64f4b851c3a13c8") }
แสดงข้อมูล
> db.filterArrayElementsDemo.find().pretty();
ผลลัพธ์:
{
"_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
"Scores": [10, 45, 67, 78, 90, 98, 99, 92]
}
คำสั่งกรอง: คืนค่าเฉพาะค่าที่อยู่ใน Scores และใน [10, 98, 99]
> db.filterArrayElementsDemo.aggregate([
{ $match: { _id: ObjectId("5cd2d582b64f4b851c3a13c8") }},
{ $project: {
Scores: { $setIntersection: ["$Scores", [10, 98, 99]] }
}
}
]);
ผลลัพธ์: เหลือเฉพาะ 10, 98, 99
{
"_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
"Scores": [10, 98, 99]
}
รายละเอียด $setIntersection
- Syntax:
{$setIntersection: [array1, array2, ...]} - คืนค่า Array ที่มี Element ปรากฏใน ทุกอาร์เรย์ที่ระบุ
- ลำดับ Element ในผลลัพธ์ไม่ได้รับประกัน (unordered)
- ลบค่าซ้ำออก (distinct) อัตโนมัติ
- รองรับ 2 อาร์เรย์ขึ้นไป
Operator เซตอื่นๆ ใน Aggregation
| Operator | ความหมาย | ตัวอย่าง |
|---|---|---|
$setUnion | ยูเนียน (รวมทุกค่า ไม่ซ้ำ) | {$setUnion: ["$a", "$b"]} |
$setIntersection | ส่วนร่วม (ค่าที่มีในทุกอาร์เรย์) | {$setIntersection: ["$a", "$b"]} |
$setDifference | ความต่าง (ค่าที่อยู่ในอาร์เรย์แรกแต่ไม่อยู่ในอาร์เรย์ถัดไป) | {$setDifference: ["$a", "$b"]} |
$setIsSubset | ตรวจสอบว่า Array แรกเป็น Subset ของ Array ที่สอง | {$setIsSubset: ["$a", "$b"]} |
$anyElementTrue | มี Element จริง (true) อย่างน้อย 1 ตัว | {$anyElementTrue: ["$boolArray"]} |
$allElementsTrue | ทุก Element เป็น true | {$allElementsTrue: ["$boolArray"]} |
กรณีใช้งานจริง
- หาสกิลที่ตรงกับ Job Requirement (Candidate Skills ∩ Job Skills)
- หาสินค้าที่ลูกค้าสนใจซ้ำ (User Wishlist ∩ Promo Items)
- กรอง Tag ที่ตรงกันระหว่างบทความ