เมื่อค้นหาสตริงที่มีอักขระพิเศษ (Special Characters) ใน MongoDB ต้องใช้ Backslash (\) เพื่อ Escape อักขระเหล่านั้นใน Regular Expression
อักขระที่ต้อง Escape ใน Regex
. * + ? ^ $ { } [ ] ( ) | \ /
ตัวอย่าง: ค้นหาสตริงที่มีเครื่องหมาย $
1. สร้างข้อมูลตัวอย่าง (UserId มี $)
> db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Smith$John123","UserFirstName":"John","UserLastName":"Smith"});
> db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Taylor$Carol983","UserFirstName":"Carol","UserLastName":"Taylor"});
> db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Doe$John999","UserFirstName":"John","UserLastName":"Doe"});
> db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Miller$David555","UserFirstName":"David","UserLastName":"Miller"});
2. แสดงข้อมูลทั้งหมด
> db.searchDocumentWithSpecialCharactersDemo.find().pretty();
{ "_id" : ..., "UserId" : "Smith$John123", "UserFirstName" : "John", "UserLastName" : "Smith" }
{ "_id" : ..., "UserId" : "Taylor$Carol983", "UserFirstName" : "Carol", "UserLastName" : "Taylor" }
{ "_id" : ..., "UserId" : "Doe$John999", "UserFirstName" : "John", "UserLastName" : "Doe" }
{ "_id" : ..., "UserId" : "Miller$David555", "UserFirstName" : "David", "UserLastName" : "Miller" }
3. ค้นหา "John" ที่มี $ นำหน้า (Escape $ ด้วย \)
> db.searchDocumentWithSpecialCharactersDemo.find({ UserId: /.*\$John.*/i }).pretty();
{ "_id" : ..., "UserId" : "Smith$John123", "UserFirstName" : "John", "UserLastName" : "Smith" }
{ "_id" : ..., "UserId" : "Doe$John999", "UserFirstName" : "John", "UserLastName" : "Doe" }
คำอธิบาย Regex
/ ... /i- Regex pattern แบบ case-insensitive.*- ตัวอักษรใดๆ จำนวน 0 หรือมาก\$- Escape เครื่องหมาย $ (ที่หมายถึง end-of-string ใน regex)John- คำที่ต้องการค้นหา.*- ตัวอักษรต่อท้ายได้อะไรก็ได้
วิธีอื่น: ใช้ $regex operator
db.collection.find({ "field": { $regex: ".*\\$John.*", $options: "i" } });
สรุป
- ใช้
\Escape อักขระพิเศษใน Regex pattern - เครื่องหมาย
$ต้อง Escape เป็น\$เพราะมีความหมายพิเศษใน Regex - ใช้ flag
iสำหรับ case-insensitive search