Operator $type: Match เอกสารตาม BSON Type
Operator $type เลือกเอกสารที่ฟิลด์มีชนิดข้อมูลตรงกับที่ระบุ ใช้ alias string หรือ numeric type code
ตัวอย่างข้อมูล (ผสม Number และ String)
> db.demo615.insert({ "Value": 100 });
> db.demo615.insert({ "Value": "100" });
> db.demo615.insert({ "Value": "300" });
> db.demo615.insert({ "Value": 300 });
Query หาเฉพาะ String
> db.demo615.find({ "Value": { $type: "string" } });
ผลลัพธ์
{ "_id": ObjectId(...), "Value": "100" }
{ "_id": ObjectId(...), "Value": "300" }
Type Aliases ทั้งหมด (MongoDB 3.2+)
| Alias | Type Number | คำอธิบาย |
|---|---|---|
double / number | 1 | 64-bit floating point |
string | 2 | UTF-8 string |
object | 3 | Embedded document |
array | 4 | Array |
binData | 5 | Binary data |
undefined | 6 | Deprecated |
objectId | 7 | ObjectId |
bool | 8 | Boolean |
date | 9 | UTC datetime |
null | 10 | Null value |
regex | 11 | Regular expression |
dbPointer | 12 | Deprecated |
javascript | 13 | JavaScript code |
symbol | 14 | Deprecated |
javascriptWithScope | 15 | JavaScript with scope |
int | 16 | 32-bit integer |
timestamp | 17 | Timestamp |
long | 18 | 64-bit integer |
decimal | 19 | 128-bit decimal |
minKey | 255 | Internal |
maxKey | 127 | Internal |
การใช้งานแบบ Array (Multiple Types)
// หา Value ที่เป็น string หรือ number
db.demo615.find({ Value: { $type: ["string", "number"] } });
// หา Value ที่เป็น int หรือ long
db.demo615.find({ Value: { $type: ["int", "long"] } });
Use Cases
- Data quality check - หาข้อมูลผิดชนิด
- Migration - ระบุเอกสารที่ต้องแปลงชนิด
- Polymorphic schema - จัดการฟิลด์ที่มีหลายชนิด
- Debug - ตรวจสอบข้อมูลที่ insert ผิด