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

การใช้ NOT และ AND พร้อมกันใน MongoDB: ทฤษฎีและตัวอย่าง

MongoDB รองรับการรวม operator $not และ $and (หรือ logic NOT X AND NOT Y) ได้ โดยเทียบเท่ากับ NOT (X AND Y) ตามกฎของ De Morgan

ตรรกะทางคณิตศาสตร์ (De Morgan's Law)

NOT X AND NOT Y = NOT (X AND Y)
NOT X OR NOT Y  = NOT (X AND Y)  // เทียบเท่ากัน
  • ถ้า X และ Y เป็นจริงทั้งคู่ → ผลลัพธ์เป็นเท็จ
  • ถ้า X หรือ Y อย่างใดอย่างหนึ่งเป็นเท็จ → ผลลัพธ์เป็นจริง

ตัวอย่างใน MongoDB

1. สร้างข้อมูลตัวอย่าง

> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"US"});
> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"UK"});
> db.NotAndDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"});
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"UK"});
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"US"});

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

{ "_id" : ..., "StudentName" : "John", "StudentCountryName" : "US" }
{ "_id" : ..., "StudentName" : "John", "StudentCountryName" : "UK" }
{ "_id" : ..., "StudentName" : "David", "StudentCountryName" : "AUS" }
{ "_id" : ..., "StudentName" : "Chris", "StudentCountryName" : "UK" }
{ "_id" : ..., "StudentName" : "Chris", "StudentCountryName" : "US" }

3. Query: NOT (StudentName = "Chris" AND StudentCountryName = "US")

เทียบเท่า: StudentName != "Chris" OR StudentCountryName != "US"

> db.NotAndDemo.find({
    $or: [
        { "StudentName": { $ne: "Chris" } },
        { "StudentCountryName": { $ne: "US" } }
    ]
}).pretty();

4. ผลลัพธ์ (เอกสารที่ไม่ใช่ Chris จาก US)

{ "_id" : ..., "StudentName" : "John", "StudentCountryName" : "US" }
{ "_id" : ..., "StudentName" : "John", "StudentCountryName" : "UK" }
{ "_id" : ..., "StudentName" : "David", "StudentCountryName" : "AUS" }
{ "_id" : ..., "StudentName" : "Chris", "StudentCountryName" : "UK" }

เอกสาร "Chris" + "US" ถูก filter ออก เพราะตรงเงื่อนไขทั้งสอง (X AND Y = true)

Operator ที่เกี่ยวข้อง

  • $not - logical NOT
  • $and - logical AND (explicit)
  • $or - logical OR
  • $nor - logical NOR (NOT OR)
  • $ne - Not Equal

สรุป

MongoDB รองรับ logic NOT และ AND ผ่าน $or + $ne (De Morgan) หรือใช้ $nor โดยตรง เขียน query ให้ตรงกับ business logic ที่ต้องการ