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

MongoDB Query: ตรวจสอบความมีอยู่ของหลายฟิลด์พร้อมกัน


ใช้ $exists ร่วมกับ $and สำหรับ Multiple Field Existence

Operator $exists ตรวจสอบว่าฟิลด์มีอยู่ในเอกสารหรือไม่ ร่วมกับ $and เพื่อตรวจสอบหลายฟิลด์พร้อมกัน

ตัวอย่างข้อมูล

> db.demo475.insertOne({ "StudentFirstName": "Chris", "StudentAge": 23 });
> db.demo475.insertOne({ "StudentFirstName": "Bob", "StudentAge": 21, "StudentCountryName": "US" });
> db.demo475.insertOne({ "StudentFirstName": "David", "StudentAge": 22 });

Query หาเอกสารที่มีครบ 3 ฟิลด์

> db.demo475.find({
  $and: [
    { "StudentFirstName": { $exists: true } },
    { "StudentAge": { $exists: true } },
    { "StudentCountryName": { $exists: true } }
  ]
});

ผลลัพธ์

{ "_id": ObjectId(...), "StudentFirstName": "Bob", "StudentAge": 21, "StudentCountryName": "US" }

รูปแบบสั้น (Implicit AND)

ใน find() เงื่อนไขหลายอย่างคั่นด้วย comma เป็น AND โดยอัตโนมัติ:

db.demo475.find({
  "StudentFirstName": { $exists: true },
  "StudentAge": { $exists: true },
  "StudentCountryName": { $exists: true }
});

$exists: true vs $exists: false

Queryความหมาย
{ field: { $exists: true } }ฟิลด์มีอยู่ (รวมถึงค่า null)
{ field: { $exists: false } }ฟิลด์ไม่มีอยู่เลย
{ field: null }ฟิลด์มีอยู่ และค่าเป็น null (หรือไม่มีฟิลด์ - พฤติกรรม legacy)

การใช้งานกับ $type

// ฟิลด์มีอยู่ และเป็น string
{ field: { $exists: true, $type: "string" } }

// ฟิลด์ไม่มี หรือเป็น null
{ $or: [{ field: { $exists: false } }, { field: null }] }

Index สำหรับ $exists

// Partial index - index เฉพาะเอกสารที่มีฟิลด์นี้
db.demo475.createIndex(
  { StudentCountryName: 1 },
  { partialFilterExpression: { StudentCountryName: { $exists: true } } }
);