ใช้ find() กับค่า Integer โดยตรง
MongoDB จัดเก็บตัวเลขเป็น BSON numeric types (int32, int64, double) สามารถ query ด้วยค่าตัวเลขได้โดยตรง ไม่ต้องแปลง
ตัวอย่างข้อมูล (รวมค่าลบ)
> db.demo472.insertOne({ "Project_Id": -101, "ProjectName": "Online Customer Tracking" });
> db.demo472.insertOne({ "Project_Id": 101, "ProjectName": "Online Banking System" });
> db.demo472.insertOne({ "Project_Id": 102, "ProjectName": "Online Library System" });
Query หา Project_Id = -101
> db.getCollection('demo472').find({ "Project_Id": -101 });
ผลลัพธ์
{ "_id": ObjectId(...), "Project_Id": -101, "ProjectName": "Online Customer Tracking" }
การ Query ตัวเลขขั้นสูง
// ช่วงค่า (Range)
db.demo472.find({ Project_Id: { $gte: 100, $lte: 200 } });
// หลายค่า (In)
db.demo472.find({ Project_Id: { $in: [-101, 101, 102] } });
// ไม่ใช่ค่าเหล่านี้
db.demo472.find({ Project_Id: { $nin: [101] } });
// Modulo (หารลงตัว)
db.demo472.find({ Project_Id: { $mod: [10, 1] } }); // Project_Id % 10 == 1
Type Sensitivity
MongoDB แยกชนิดตัวเลข: 101 (int) ≠ "101" (string) ≠ 101.0 (double)
// หาเฉพาะ int32
db.demo472.find({ Project_Id: { $type: "int" } });
// หา int32, int64, double ทั้งหมด
db.demo472.find({ Project_Id: { $type: "number" } });
Index สำหรับ Numeric Field
db.demo472.createIndex({ Project_Id: 1 }); // Single field
db.demo472.createIndex({ Project_Id: 1, ProjectName: 1 }); // Compound
ข้อควรระวัง
- JavaScript Number เป็น double เสมอ - driver จะแปลงเป็น int32/int64 ตามค่า
- ใช้ NumberInt() หรือ NumberLong() ใน shell เพื่อระบุชนิดชัดเจน
NumberInt(101)= int32,NumberLong(101)= int64