ใช้ $exists กับ Dot Notation ตรวจสอบ Index แรกของอาร์เรย์
เพื่อเช็คว่าอาร์เรย์มีข้อมูล (ไม่ใช่ Empty Array) ใช้ { 'arrayField.0': { $exists: true } } - ถ้ามี Index 0 แสดงว่ามีอย่างน้อย 1 สมาชิก
ตัวอย่างข้อมูล: คะแนนผู้เล่น (บางคนยังไม่มีคะแนน)
> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]});
> db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]});
> db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]});
> db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]});
คิวรี: นับจำนวนผู้เล่นที่มีคะแนน (PlayerScores ไม่ใช่ Empty Array)
> db.checkIfValueDemo.find({'PlayerScores.0': {$exists: true}}).count();
ผลลัพธ์
2
(John Smith และ Carol Taylor มีคะแนน)
วิธีอื่นๆ
// 1. ใช้ $size (แม่นยำกว่า แต่ต้อง MongoDB 2.6+)
db.checkIfValueDemo.find({ PlayerScores: { $not: { $size: 0 } } }).count();
// 2. ใช้ $expr + $gt (MongoDB 3.6+)
db.checkIfValueDemo.find({ $expr: { $gt: [{ $size: "$PlayerScores" }, 0] } }).count();
// 3. ใช้ $ne กับ Empty Array (ไม่แนะนำ - ไม่ใช้ Index ได้)
db.checkIfValueDemo.find({ PlayerScores: { $ne: [] } }).count();
สรุปการเลือกใช้
| วิธี | รองรับ Index | เวอร์ชัน | หมายเหตุ |
|---|---|---|---|
array.0: { $exists: true } | ✅ ใช่ | ทุกเวอร์ชัน | เร็วที่สุด สำหรับเช็ค "มีข้อมูลหรือไม่" |
$size: 0 + $not | ❌ ไม่ได้ | 2.6+ | แม่นยำ แต่ Full Scan |
$expr + $size | ❌ ไม่ได้ | 3.6+ | ยืดหยุ่นกว่า |