Regex ทำงานบน String ไม่ทำงานโดยตรงบน Integer ต้องใช้ $where ร่วม JavaScript .test() เพื่อแปลงตัวเลขเป็น String แล้วค่อย Match
ไวยากรณ์
db.yourCollectionName.find({
$where: "/^yourIntegerPattern.*/.test(this.yourFieldName)"
});
สร้างข้อมูลตัวอย่าง
> db.regExpOnIntegerDemo.insertOne({"StudentId": 2341234});
> db.regExpOnIntegerDemo.insertOne({"StudentId": 123234});
> db.regExpOnIntegerDemo.insertOne({"StudentId": 9871234});
> db.regExpOnIntegerDemo.insertOne({"StudentId": 2345612});
> db.regExpOnIntegerDemo.insertOne({"StudentId": 1239812345});
แสดงเอกสารทั้งหมด
> db.regExpOnIntegerDemo.find().pretty();
Regex Search: หา StudentId เริ่มต้นด้วย 123
> db.regExpOnIntegerDemo.find({
$where: "/^123.*/.test(this.StudentId)"
});
ผลลัพธ์ (StudentId เริ่มต้น 123)
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }
หมายเหตุ: $where ใช้ JavaScript Evaluation ช้ากว่า Query ปกติ มาก สำหรับ Production ควรเก็บค่าเป็น String แทน หรือใช้ Text Search / Atlas Search แทน