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

จับคู่ Element ใน Array MongoDB ด้วย $or และ limit(1)

ใช้ Operator $or ร่วมกับ limit(1) เพื่อค้นหาเอกสารที่มี Element ใน Array ตรงกับเงื่อนไขใดเงื่อนไขหนึ่ง และคืนค่าแค่เอกสารแรกที่เจอ

สร้างคอลเลกชันและข้อมูลตัวอย่าง (Array of Objects)

> db.matchElementInArrayDemo.insertOne({
    "StudentName": "Chris",
    "StudentOtherDetails": [
      {"StudentCountryName": "US", "StudentSkills": "MongoDB"},
      {"StudentCountryName": "UK", "StudentSkills": "Java"}
    ]
  });
{ "acknowledged": true, "insertedId": ObjectId("5cd423282cba06f46efe9ee2") }

> db.matchElementInArrayDemo.insertOne({
    "StudentName": "Chris",
    "StudentOtherDetails": [
      {"StudentCountryName": "AUS", "StudentSkills": "PHP"},
      {"StudentCountryName": "US", "StudentSkills": "MongoDB"}
    ]
  });
{ "acknowledged": true, "insertedId": ObjectId("5cd423412cba06f46efe9ee3") }

แสดงข้อมูลทั้งหมด

> db.matchElementInArrayDemo.find().pretty();

ผลลัพธ์: 2 เอกสาร ทั้งคู่มี Element ที่ตรงเงื่อนไข

Query: หาเอกสารที่มี Country = "US" OR Skills = "MongoDB" ใน Array (คืนแค่ 1 อัน)

> db.matchElementInArrayDemo.find({
  $or: [
    {"StudentOtherDetails.StudentCountryName": "US"},
    {"StudentOtherDetails.StudentSkills": "MongoDB"}
  ]
}).limit(1);

ผลลัพธ์: เอกสารแรกที่เจอ (ทั้ง 2 เอกสารก็ Match แต่ Limit 1)

{
  "_id": ObjectId("5cd423282cba06f46efe9ee2"),
  "StudentName": "Chris",
  "StudentOtherDetails": [
    {"StudentCountryName": "US", "StudentSkills": "MongoDB"},
    {"StudentCountryName": "UK", "StudentSkills": "Java"}
  ]
}

การทำงานของ Dot Notation บน Array of Objects

  • StudentOtherDetails.StudentCountryName → MongoDB ตรวจสอบทุก Object ใน Array ว่ามีฟิลด์นี้ตรงเงื่อนไขหรือไม่
  • เหมือนกับการ $elemMatch แบบ Implicit สำหรับ Single Field Condition
  • $or รวมเงื่อนไข: Match หาก Element ใด Element หนึ่งตรงเงื่อนไขไหนเงื่อนไขหนึ่ง

⚠️ ข้อควรระวัง: $or vs $elemMatch

// $or: Element คนละตัวก็ Match ได้
// Doc: [{country: "US", skill: "Java"}, {country: "UK", skill: "MongoDB"}]
// Query: $or: [{country: "US"}, {skill: "MongoDB"}] → MATCH (Element ต่างกัน)

// $elemMatch: ต้องเป็น Object เดียวกันที่ Match ทุกเงื่อนไข
// Query: {StudentOtherDetails: {$elemMatch: {country: "US", skill: "MongoDB"}}} → NO MATCH

เมื่อไหร่ควรใช้ $elemMatch

  • ต้องการจับคู่ หลายฟิลด์ใน Object เดียวกัน ภายใน Array
  • Query: {arrayField: {$elemMatch: {field1: val1, field2: val2}}}

Performance: limit(1)

  • หยุดการสแกนทันทีที่เจอ Match แรก
  • เหมาะสำหรับ Check Exists / Find One
  • ร่วมกับ Index ได้ หาก Query Selective