ใช้โอเปอเรเตอร์ $exists
โอเปอเรเตอร์ $exists ตรวจสอบว่าฟิลด์ระบุมีอยู่ในเอกสารหรือไม่ ค่า true = มีอยู่, false = ไม่มี
ตัวอย่างข้อมูล
สร้างคอลเลกชัน checkFieldExistsOrNotDemo ที่มีฟิลด์ต่างกันในแต่ละเอกสาร:
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Larry"});
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"John","StudentAge":21});
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"US"});
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"UK","StudentHobby":["Teaching","Photography"]});
Case 1: ฟิลด์มีอยู่ (StudentHobby)
> db.checkFieldExistsOrNotDemo.find({'StudentHobby': {'$exists': true}}).pretty();
ผลลัพธ์: คืนเฉพาะเอกสารของ Robert ที่มีฟิลด์ StudentHobby
Case 2: ฟิลด์ไม่มีอยู่ (StudentTechnicalSubject)
> db.checkFieldExistsOrNotDemo.find({'StudentTechnicalSubject': {'$exists': true}}).pretty();
ผลลัพธ์: ไม่มีเอกสารใดคืนกลับมา (empty result)
ค้นหาที่ไม่มีฟิลด์
ใช้ {$exists: false} เพื่อหาเอกสารที่ขาดฟิลด์นั้น:
db.collection.find({"fieldName": {$exists: false}})