การตรวจสอบว่า Field เป็น Number (Numeric Type) ใน MongoDB
ใช้ ออเปอเรเตอร์ $type ร่วมกับ BSON Type Alias "number" เพื่อค้นหาเอกสารที่ฟิลด์มีค่าเป็นตัวเลข (Integer, Long, Double, Decimal)
ไวยากรณ์
db.yourCollectionName.find({yourFieldName: {$type: "number"}}).pretty();
ตัวอย่างการสร้างคอลเลกชันและเพิ่มข้อมูล (Mixed Types)
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"John","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec75dd628fa4220163b83") }
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Chris","StudentMathScore":98,"StudentCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec77cd628fa4220163b84") }
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Robert","StudentCountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec7a4d628fa4220163b85") }
> db.checkIfFieldIsNumberDemo.insertOne({"StudentId":101,"StudentName":"Larry","StudentCountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec7ccd628fa4220163b86") }
แสดงข้อมูลทั้งหมด
> db.checkIfFieldIsNumberDemo.find().pretty();
ผลลัพธ์ (Field Types หลากหลาย):
{ "_id" : ObjectId("5c9ec75dd628fa4220163b83"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5c9ec7a4d628fa4220163b85"), "StudentName" : "Robert", "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5c9ec7ccd628fa4220163b86"), "StudentId" : 101, "StudentName" : "Larry", "StudentCountryName" : "AUS" }
ค้นหาเอกสารที่ StudentMathScore เป็น Number
> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type: "number"}}).pretty();
ผลลัพธ์ (พบเฉพาะ Chris ที่มี StudentMathScore = 98):
{ "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" }
คำอธิบาย $type Operator
- $type : เลือกเอกสารตาม BSON Type ของ Field
- "number" : Alias สำหรับ Numeric Types ทั้งหมด (Double, Int32, Int64, Decimal128)
- Case Insensitive: "number", "Number", "NUMBER" ใช้ได้หมด
BSON Numeric Types และ Aliases
| BSON Type | Type Number | Alias | คำอธิบาย |
|---|---|---|---|
| Double | 1 | "double", "number" | 64-bit Floating Point (Default สำหรับตัวเลขใน Shell) |
| Int32 | 16 | "int", "number" | 32-bit Signed Integer |
| Int64 | 18 | "long", "number" | 64-bit Signed Integer (NumberLong) |
| Decimal128 | 19 | "decimal", "number" | 128-bit Decimal (NumberDecimal) |