ใช้ $ne: null หาเอกสารที่ฟิลด์ ไม่ใช่ Null
ใน MongoDB ค่า null มีความหมายพิเศษ: Query { field: null } จะ Match ทั้ง Field ที่เป็น Null และ Field ที่ Missing (ไม่มีฟิลด์นั้น) ใช้ $ne: null เพื่อกรองเฉพาะที่มีค่าจริง
ตัวอย่างข้อมูล
> db.queryingNullDemo.insertOne({
"StudentName": "Larry",
"StudentDetails": { "StudentAge": 21, "StudentSubject": "MongoDB" }
});
> db.queryingNullDemo.insertOne({
"StudentName": "Sam",
"StudentDetails": { "StudentAge": 23, "StudentSubject": null }
});
คิวรี: หาที่ StudentSubject ไม่ใช่ Null
> db.queryingNullDemo.find({ 'StudentDetails.StudentSubject': { $ne: null } });
ผลลัพธ์: ได้แค่ Larry (Sam เป็น Null ถูกกรองออก)
{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
"StudentName" : "Larry",
"StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } }
Null Query Behavior Summary
| Query | Match Field = null | Match Field Missing | Match Field = "value" |
|---|---|---|---|
{ field: null } | ✅ | ✅ | ❌ |
{ field: { $eq: null } } | ✅ | ✅ | ❌ |
{ field: { $ne: null } } | ❌ | ❌ | ✅ |
{ field: { $in: [null] }, field: { $exists: true } } | ✅ | ❌ | ❌ |
{ field: { $exists: true, $ne: null } } | ❌ | ❌ | ✅ |
Best Practices
- ใช้
{ field: { $ne: null } }สำหรับ "มีค่า ไม่ใช่ Null" - ใช้
{ field: { $in: [null], $exists: true } }สำหรับ "มีฟิลด์ และเป็น Null" - ใช้
{ field: { $exists: false } }สำหรับ "ไม่มีฟิลด์นี้" - หลีกเลี่ยง
{ field: null }เพราะ Match Missing Field ด้วย (มักทำให้ Bug)
ใน Aggregation
db.queryingNullDemo.aggregate([
{ $match: { "StudentDetails.StudentSubject": { $ne: null } } },
{ $project: { StudentName: 1, Subject: "$StudentDetails.StudentSubject" } }
]);