หากต้องการตรวจสอบว่ามีฟิลด์ใดใน MongoDB หรือไม่ คุณสามารถใช้ตัวดำเนินการ $exists
เพื่อให้เข้าใจแนวคิดข้างต้น ให้เราสร้างคอลเลกชันพร้อมกับเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba4136de59bd9de063a1")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba4e36de59bd9de063a2")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba6536de59bd9de063a3")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"UK","StudentHobby":["Teaching","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba9d36de59bd9de063a4")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.checkFieldExistsOrNotDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{ "_id" : ObjectId("5c92ba4136de59bd9de063a1"), "StudentName" : "Larry" }
{
"_id" : ObjectId("5c92ba4e36de59bd9de063a2"),
"StudentName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c92ba6536de59bd9de063a3"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
"StudentName" : "Robert",
"StudentAge" : 21,
"StudentCountryName" : "UK",
"StudentHobby" : [
"Teaching",
"Photography"
]
} นี่คือแบบสอบถามเพื่อตรวจสอบว่ามีฟิลด์ใน MongoDB หรือไม่
กรณีที่ 1 − เมื่อฟิลด์นั้นมีอยู่
แบบสอบถามมีดังนี้ −
> db.checkFieldExistsOrNotDemo.find({ 'StudentHobby' : { '$exists' : true }}).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
"StudentName" : "Robert",
"StudentAge" : 21,
"StudentCountryName" : "UK",
"StudentHobby" : [
"Teaching",
"Photography"
]
} กรณีที่ 2 − เมื่อไม่มีเขตข้อมูล
แบบสอบถามมีดังนี้:
> db.checkFieldExistsOrNotDemo.find({ 'StudentTechnicalSubject' : { '$exists' : true }}).pretty(); คุณจะไม่ได้รับอะไรเลยเมื่อไม่มีฟิลด์