ใช้ Operator $and เพื่อระบุเงื่อนไขหลายอย่างที่ต้องตรงพร้อมกันใน Array of Objects: ต้องมี Element ที่ id=102 และ Element ที่ id=103 ใน Array เดียวกัน
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.twoSpecificIdsDemo.insertOne({
PlayerId: 1,
"PlayerDetails": [
{"id": 100, "PlayerName": "Chris"},
{"id": 101, "PlayerName": "Sam"},
{"id": 102, "PlayerName": "Robert"},
{"id": 103, "PlayerName": "Carol"}
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3e130edc6604c74817ce4") }
> db.twoSpecificIdsDemo.insertOne({
PlayerId: 1,
"PlayerDetails": [
{"id": 104, "PlayerName": "Mike"},
{"id": 105, "PlayerName": "Bob"},
{"id": 102, "PlayerName": "Ramit"},
{"id": 106, "PlayerName": "David"}
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3e167edc6604c74817ce5") }
แสดงข้อมูลทั้งหมด
> db.twoSpecificIdsDemo.find().pretty();
ผลลัพธ์: 2 เอกสาร ทั้งคู่มี id=102 แต่เพียงเอกสารแรกมี id=103
Query: หาเอกสารที่มี id=102 และ id=103 ใน Array เดียวกัน
> db.twoSpecificIdsDemo.find({
$and: [
{"PlayerDetails.id": 102},
{"PlayerDetails.id": 103}
]
}).pretty();
ผลลัพธ์: เฉพาะเอกสารแรก (มีทั้ง 102 และ 103)
{
"_id": ObjectId("5cd3e130edc6604c74817ce4"),
"PlayerId": 1,
"PlayerDetails": [
{"id": 100, "PlayerName": "Chris"},
{"id": 101, "PlayerName": "Sam"},
{"id": 102, "PlayerName": "Robert"},
{"id": 103, "PlayerName": "Carol"}
]
}
ทำไมต้องใช้ $and?
- Query ปกติ
{"PlayerDetails.id": 102, "PlayerDetails.id": 103}จะถูก Merge ให้เหลือ Key เดียว (Key ซ้ำใน Object ไม่ได้) $andบังคับให้ประเมินเงื่อนไขแยกกัน แล้วรวมด้วย AND Logic- แต่ละเงื่อนไข
{"PlayerDetails.id": 102}ตรวจสอบว่า Array มี Element ใดที่ id=102 - ทั้งสองเงื่อนไขต้อง True พร้อมกัน → Array ต้องมีทั้ง 102 และ 103
ตัวอย่างเพิ่มเติม
// หาที่มี id 102, 103, 104 ทั้ง 3 ตัว
db.coll.find({
$and: [
{"PlayerDetails.id": 102},
{"PlayerDetails.id": 103},
{"PlayerDetails.id": 104}
]
});
// ใช้ $all กับ Array of Values (สำหรับ Array of Primitives)
// ไม่ได้สำหรับ Array of Objects โดยตรง
// แต่ถ้า Project เฉพาะ id ก่อนได้:
db.coll.aggregate([
{$project: {ids: "$PlayerDetails.id"}},
{$match: {ids: {$all: [102, 103]}}}
]);
⚠️ ข้อจำกัด: Same Element Matching
Query นี้ Match หาก Element คนละตัว ก็ได้ (102 อยู่ Element ที่ 3, 103 อยู่ Element ที่ 4)
หากต้องการ Object เดียวที่มีทั้ง 2 ฟิลด์ (ไม่เป็นไปได้ในโครงสร้างนี้ เพราะ 1 Object มี 1 id) → ใช้ $elemMatch สำหรับหลายฟิลด์ใน Object เดียวกัน