การตรวจสอบว่า Field มีอยู่ใน MongoDB ด้วย $exists Operator
ใช้ ออเปอเรเตอร์ $exists เพื่อตรวจสอบว่า Field นั้นมีอยู่ใน Document หรือไม่ โดยไม่สนใจค่าของ Field (แม้จะเป็น null, empty string, หรือค่าใดๆ ก็ตาม)
ไวยากรณ์
db.yourCollectionName.find({yourFieldName: {$exists: true}});
ตัวอย่างการสร้างคอลเลกชันและเพิ่มข้อมูล
> db.determineFieldExistsDemo.insertOne({"ClientName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9eb245d628fa4220163b75") }
> db.determineFieldExistsDemo.insertOne({"ClientName":"Larry","ClientAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9eb25cd628fa4220163b76") }
> db.determineFieldExistsDemo.insertOne({"ClientName":"Mike","ClientCountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9eb26fd628fa4220163b77") }
> db.determineFieldExistsDemo.insertOne({"ClientName":"Sam","ClientAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9eb286d628fa4220163b78") }
แสดงข้อมูลทั้งหมด
> db.determineFieldExistsDemo.find().pretty();
ผลลัพธ์ (Schema ต่างกันใน Collection เดียวกัน):
{ "_id" : ObjectId("5c9eb245d628fa4220163b75"), "ClientName" : "John" }
{ "_id" : ObjectId("5c9eb25cd628fa4220163b76"), "ClientName" : "Larry", "ClientAge" : 23 }
{ "_id" : ObjectId("5c9eb26fd628fa4220163b77"), "ClientName" : "Mike", "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5c9eb286d628fa4220163b78"), "ClientName" : "Sam", "ClientAge" : 24 }
ค้นหาเอกสารที่มี Field ClientCountryName
> db.determineFieldExistsDemo.find({ClientCountryName: {$exists: true}}).pretty();
ผลลัพธ์ (พบเฉพาะ Mike):
{ "_id" : ObjectId("5c9eb26fd628fa4220163b77"), "ClientName" : "Mike", "ClientCountryName" : "UK" }
คำอธิบาย $exists
- {$exists: true} : Field มีอยู่ใน Document (Match ทุกค่า: null, "", 0, false, [], {}, etc.)
- {$exists: false} : Field ไม่อยู่ใน Document (Missing Field)
ตารางเปรียบเทียบ $exists กับ Operators อื่นๆ
| Query | Field มีค่า "value" | Field = null | Field = "" | Field = 0 | Field = false | Field Missing |
|---|---|---|---|---|---|---|
| {field: {$exists: true}} | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| {field: {$exists: false}} | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| {field: null} | ❌ | ✅ | ❌ | ❌ | ❌ | ✅* |
| {field: {$ne: null}} | ✅ | ❌ | ✅ | ✅ | ✅ | ✅* |
| {field: {$nin: [null, ""]}} | ✅ | ❌ | ❌ | ✅ | ✅ | ✅* |
* MongoDB ถือ Missing Field เทียบเท่า null ในบาง Operator
กรณี Nested Field (Dot Notation)
// ตรวจสอบ Nested Field
db.collection.find({ "address.city": { $exists: true } });
// ตรวจสอบ Object Parent
db.collection.find({ "address": { $exists: true } });
กรณี Array Field
// Array Field มีอยู่ (แม้ว่าง [])
db.collection.find({ "tags": { $exists: true } });
// Array Field มี Element (Non-empty) - ใช้ $ne: []
db.collection.find({ "tags": { $exists: true, $ne: [] } });
// หรือใช้ $size
db.collection.find({ "tags": { $exists: true, $not: { $size: 0 } } });
การใช้งานร่วมกับ Projection
// ดึงเฉพาะ Field ที่มีอยู่
db.collection.find({ optionalField: { $exists: true } }, { optionalField: 1, _id: 0 });
// Conditional Projection (Aggregation)
db.collection.aggregate([
{ $project: {
hasOptional: { $cond: [{ $gt: [{ $size: { $ifNull: ["$optionalField", []] } }, 0] }, true, false] }
}}
]);
Schema Validation (MongoDB 3.2+) - บังคับ Field
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "name"], // บังคับ Field นี้ต้องมี
properties: {
email: { bsonType: "string" },
name: { bsonType: "string" },
phone: { bsonType: "string" } // Optional
}
}
}
});
Best Practices
- ใช้ $exists: true เมื่อต้องการรู้ว่า Field "มีอยู่จริง" (Schema Validation)
- ใช้ $exists: false หา Document ที่ข้อมูลไม่ครบ (Data Quality Check)
- รวมกับ $ne: null หรือ $ne: "" ถ้าต้องการ Field ที่ "มีค่าจริง"
- สร้าง Partial Index สำหรับ Field ที่มีไม่ครบ:
{ partialFilterExpression: { field: { $exists: true } } }
$exists เป็นเครื่องมือพื้นฐานสำคัญในการจัดการ Schema-less Data และ Data Quality