ใช้ Regex ใน find() เพื่อค้นหาข้อความในฟิลด์
MongoDB รองรับการค้นหาข้อความด้วย Regular Expression (Regex) โดยตรงในคำสั่ง find() โดยใช้รูปแบบ /pattern/ หรืออ็อปชัน $regex
ตัวอย่างข้อมูลทดสอบ
> db.demo409.insertOne({ "Name": "John Doe" });
> db.demo409.insertOne({ "Name": "Chris Brown" });
> db.demo409.insertOne({ "Name": "Robert Doe" });
> db.demo409.insertOne({ "Name": "David Brown" });
แสดงข้อมูลทั้งหมด
> db.demo409.find();
ผลลัพธ์:
{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "Chris Brown" }
{ "_id": ObjectId("..."), "Name": "Robert Doe" }
{ "_id": ObjectId("..."), "Name": "David Brown" }
คำสั่งค้นหาชื่อที่มีคำว่า "Doe"
> db.demo409.find({ Name: /Doe/ });
ผลลัพธ์ที่ได้
{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "Robert Doe" }
รูปแบบการใช้ Regex ใน MongoDB
| รูปแบบ | คำอธิบาย |
|---|---|
{ field: /pattern/ } | Short syntax (Case-sensitive) |
{ field: /pattern/i } | Case-insensitive |
{ field: { $regex: "pattern", $options: "i" } } | Explicit syntax |
{ field: { $regex: /^John/ } } | ขึ้นต้นด้วย John (ใช้ดัชนีได้) |
ข้อควรระวังเรื่องประสิทธิภาพ
- Regex ที่ไม่ใช่ prefix pattern (เช่น
/Doe/,/John$/) จะไม่ใช้ดัชนีได้ -> ทำ Collection Scan - สำหรับการค้นหาข้อความจริงจัง ควรใช้ Text Index แทน
- หลีกเลี่ยง Regex ที่ซับซ้อนเกินไปบนข้อมูลขนาดใหญ่