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

วิธีค้นหา Document ที่ไม่มี Field ที่ระบุใน MongoDB

การค้นหา Document ที่ไม่มี Field โดยใช้ $exists

ใช้ Operator $exists: false เพื่อค้นหา Document ที่ไม่มี Field ที่ระบุ

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") }

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

> db.findDocumentNonExistenceFieldDemo.find().pretty();
{ "_id" : ObjectId("5c8a5c629064dcd4a68b70e8"), "StudentName" : "John", "StudentAge" : 25 }
{ "_id" : ObjectId("5c8a5c809064dcd4a68b70e9"), "StudentName" : "David", "StudentAge" : 26, "StudentMathMarks" : 78 }

ค้นหา Document ที่ไม่มี Field StudentMathMarks

> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty();
{ "_id" : ObjectId("5c8a5c629064dcd4a68b70e8"), "StudentName" : "John", "StudentAge" : 25 }

ผลลัพธ์แสดงเฉพาะ Document ของ John ที่ไม่มี Field StudentMathMarks