กรองอาร์เรย์ซับเอกสารด้วย $setIsSubset ใน Aggregation
ตัวดำเนินการ $setIsSubset ใช้ตรวจสอบว่าชุดค่าหนึ่งเป็นสับเซต (Subset) ของอีกชุดหนึ่งหรือไม่ ใช้ร่วมกับ $filter ใน Aggregation Pipeline เพื่อกรององค์ประกอบในอาร์เรย์
ตัวอย่างข้อมูลทดสอบ
> db.demo407.insertOne({
Name: "Chris",
"details": [
{ id: 100 },
{ id: 110 },
{ id: 130 }
]
});
แสดงข้อมูล
> db.demo407.find().pretty();
ผลลัพธ์:
{
"_id": ObjectId("5e70dffe15dc524f70227677"),
"Name": "Chris",
"details": [
{ "id": 100 },
{ "id": 110 },
{ "id": 130 }
]
}
คำสั่งกรอง details ที่ id อยู่ใน [100, 130]
> db.demo407.aggregate([
{ $match: {} },
{ $project: {
"details": {
$filter: {
input: "$details",
as: "output",
cond: { $setIsSubset: [["$$output.id"], [100, 130]] }
}
}
}}
]);
ผลลัพธ์ที่ได้
{ "_id": ObjectId("5e70dffe15dc524f70227677"), "details": [ { "id": 100 }, { "id": 130 } ] }
คำอธิบาย
- $filter: วนลูปผ่านอาร์เรย์ details
- input: "$details": อาร์เรย์ต้นทาง
- as: "output": ตัวแปรสำหรับแต่ละองค์ประกอบ
- cond: { $setIsSubset: [["$$output.id"], [100, 130]] }: ตรวจสอบว่าเซตค่า id ขององค์ประกอบนั้น เป็นสับเซตของ [100, 130] หรือไม่
การใช้งาน $setIsSubset
{ $setIsSubset: [ คืนค่า true ถ้า array1 เป็นสับเซตของ array2 (ทุกค่าใน array1 ต้องมีใน array2)
ในที่นี้ ["$$output.id"] เป็นอาร์เรย์ที่มี 1 ค่า (id ขององค์ประกอบปัจจุบัน) ตรวจสอบว่าค่านั้นอยู่ใน [100, 130] หรือไม่