ในการค้นหาเอกสารโดยไม่มีฟิลด์ใน MongoDB ไวยากรณ์จะเป็นดังนี้ -
db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty(); เพื่อให้เข้าใจไวยากรณ์ข้างต้น ให้เราสร้างคอลเลกชันด้วยเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"John","StudentAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a5c629064dcd4a68b70e8")
}
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"David","StudentAge":26,"StudentMathMarks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a5c809064dcd4a68b70e9")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.findDocumentNonExistenceFieldDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
"StudentName" : "David",
"StudentAge" : 26,
"StudentMathMarks" : 78
} นี่คือการสืบค้นเพื่อค้นหาเอกสารโดยไม่มีฟิลด์ -
> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}