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

รวมเงื่อนไข AND และ OR ใน MongoDB Query

MongoDB รองรับการรวม Operator $and และ $or เพื่อสร้าง Query Logic ที่ซับซ้อนได้ โดย $and ทำงานแบบ AND ทุกเงื่อนไข และ $or ทำงานแบบ OR ระหว่างเงื่อนไข

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

> db.combinedAndOrDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentSkill":"MongoDB"});
{ "acknowledged": true, "insertedId": ObjectId("5cd306dcb64f4b851c3a13e2") }
> db.combinedAndOrDemo.insertOne({"StudentFirstName":"Larry","StudentAge":21,"StudentSkill":"MySQL"});
{ "acknowledged": true, "insertedId": ObjectId("5cd306f3b64f4b851c3a13e3") }
> db.combinedAndOrDemo.insertOne({"StudentFirstName":"Sam","StudentAge":24,"StudentSkill":"SQL Server"});
{ "acknowledged": true, "insertedId": ObjectId("5cd30701b64f4b851c3a13e4") }

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

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

ผลลัพธ์: 3 เอกสาร

Query: รวม AND และ OR

หาเอกสารที่ (StudentFirstName = "John" AND _id = ObjectId(...)) OR (StudentSkill = "MongoDB")

> db.combinedAndOrDemo.find({
  "$or": [
    {"$and": [
      {"StudentFirstName": "John"},
      {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}
    ]},
    {"StudentSkill": "MongoDB"}
  ]
});

ผลลัพธ์: พบ John (ตรงเงื่อนไขแรก และสอง)

{
  "_id": ObjectId("5cd306dcb64f4b851c3a13e2"),
  "StudentFirstName": "John",
  "StudentAge": 23,
  "StudentSkill": "MongoDB"
}

การทำงานของ Query นี้

  • เงื่อนไขที่ 1 ($and): ต้องเป็น John และ _id ตรงกัน → Match John
  • เงื่อนไขที่ 2: Skill = MongoDB → Match John (ซ้ำ)
  • $or รวม: Match หากตรงเงื่อนไขไหนเงื่อนไขหนึ่ง
  • Larry (MySQL) และ Sam (SQL Server) ไม่ตรงทั้งคู่

รูปแบบย่อ (Implicit AND)

ใน MongoDB Query Object ทั่วไป (ไม่มี $or) เป็น Implicit AND แล้ว:

// นี้คือ AND ทั้ง 3 เงื่อนไข
db.coll.find({StudentFirstName: "John", StudentAge: 23, StudentSkill: "MongoDB"});

ตัวอย่าง $or แบบง่าย

// หา คนชื่อ John หรือ คนอายุ 21
db.coll.find({$or: [{StudentFirstName: "John"}, {StudentAge: 21}]});

ตัวอย่าง $and แบบชัดเจน (Explicit)

// จำเป็นต้องใช้ $and เมื่อมีเงื่อนไขซ้ำฟิลด์เดียวกัน
db.coll.find({$and: [{age: {$gte: 18}}, {age: {$lte: 65}}]});

Performance Tip

  • วางเงื่อนไขที่ Selective ที่สุด (Filter ได้เยอะที่สุด) ไว้ข้างหน้าใน $or
  • สร้าง Index รองรับเงื่อนไขที่ใช้บ่อย
  • หลีกเลี่ยง $or ที่มีเงื่อนไขเยอะมาก (Performance ลดลง)