ใช้ $regex สำหรับ Pattern Matching
Operator $regex ช่วยค้นหาข้อความที่ตรงกับรูปแบบ (pattern) รองรับ Regular Expressions ทั้งหมด พร้อม options เช่น case-insensitive
ตัวอย่างข้อมูล
> db.demo469.insertOne({ "StudentName": "John Doe" });
> db.demo469.insertOne({ "StudentName": "Chris Brown" });
> db.demo469.insertOne({ "StudentName": "John Smith" });
> db.demo469.insertOne({ "StudentName": "Jace Doe" });
> db.demo469.insertOne({ "StudentName": "David Miller" });
Query ค้นหาชื่อที่มี "john" (ไม่สนใจพิมพ์เล็ก/ใหญ่)
> db.demo469.find({ 'StudentName': { '$regex': 'john', '$options': 'i' } });
ผลลัพธ์
{ "_id": ObjectId(...), "StudentName": "John Doe" }
{ "_id": ObjectId(...), "StudentName": "John Smith" }
Regex Options
| Option | คำอธิบาย |
|---|---|
i | Case-insensitive (ไม่สนใจพิมพ์เล็ก/ใหญ่) |
m | Multiline (^ และ $ match เริ่ม/จบบรรทัด) |
x | Extended (ignore whitespace, อนุญาต comment) |
s | Dot matches newline (. match \n ได้) |