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

ตรวจสอบฟิลด์ใน MongoDB ว่าเป็น Empty Array [] หรือ Empty Object {} ด้วย $gt และ $exists

ใช้ Query ร่วมกัน 2 เงื่อนไข: $gt: {} (มากกว่า Empty Object) และ $exists: false บน Index 0 เพื่อแยกแยะระหว่าง Empty Object {} และ Empty Array []

ไวยากรณ์

db.collection.find({
  "yourField": {$gt: {}},
  "yourField.0": {$exists: false}
})

สร้างคอลเลกชันและข้อมูลทดสอบ (หลายกรณี)

> db.checkFieldDemo.insert([
  {_id: 1010, StudentDetails: {}},
  {_id: 1011, StudentDetails: [{"StudentId": 1}]},
  {_id: 1012, StudentDetails: [{}]},
  {_id: 1013},
  {_id: 1014, StudentDetails: null},
  {_id: 1015, StudentDetails: {"StudentId": 1}}
]);
BulkWriteResult({"nInserted": 6})

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

> db.checkFieldDemo.find().pretty();

ผลลัพธ์:

{"_id": 1010, "StudentDetails": {}}
{"_id": 1011, "StudentDetails": [{"StudentId": 1}]}
{"_id": 1012, "StudentDetails": [{}]}
{"_id": 1013}
{"_id": 1014, "StudentDetails": null}
{"_id": 1015, "StudentDetails": {"StudentId": 1}}

Query: หาเอกสารที่ StudentDetails เป็น Non-Empty Object (มีฟิลด์) แต่ไม่ใช่ Array

> db.checkFieldDemo.find({
  "StudentDetails": {$gt: {}},
  "StudentDetails.0": {$exists: false}
});

ผลลัพธ์: เฉพาะ _id 1015 (Object ที่มีฟิลด์ StudentId)

{"_id": 1015, "StudentDetails": {"StudentId": 1}}

ตรรกะของ Query นี้

_idStudentDetails$gt: {}.0 $exists: falseMatch?
1010{}False (Empty Object ไม่ > {})TrueNo
1011[{"StudentId":1}]True (Array > {})False (มี Index 0)No
1012[{}] TrueFalse (มี Index 0)No
1013MissingFalseTrueNo
1014nullFalseTrueNo
1015{StudentId: 1}True (Non-empty Object > {})True (ไม่มี Index 0)Yes

Query Patterns อื่นๆ สำหรับตรวจสอบ Array/Object

// เป็น Array (ว่างหรือไม่ว่าง)
{"field.0": {$exists: true}}

// เป็น Non-empty Array
{"field.0": {$exists: true}}

// เป็น Empty Array
{"field": {$eq: []}}  // หรือ {"field": {$size: 0}}

// เป็น Object (ว่างหรือไม่ว่าง)
{"field": {$type: "object"}}

// เป็น Non-empty Object
{"field": {$not: {$size: 0}}, $type: "object"}  // MongoDB 3.6+

// เป็น Null หรือ Missing
{"field": {$in: [null, undefined]}}  // หรือ {"field": {$eq: null}} (รวม Missing)