MongoDB ไร้การรองรับการใช้ field value เป็น regex pattern โดยตรงใน $regex แต่สามารถทำได้ด้วย $indexOfCP (code point index) ใน aggregate pipeline เพื่อตรวจสอบว่า field หนึ่งมีค่าอีก field หนึ่งเป็น substring หรือไม่
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.demo88.insertOne({
"Name": "Chris",
"PassoutYear": "2020",
"websiteName": "chris.shop.com/Carol-2020-"
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2c14c471bf0181ecc422b1") }
> db.demo88.insertOne({
"Name": "David",
"PassoutYear": "2010",
"websiteName": "david.bigshop.com/David-2010-"
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2c14c571bf0181ecc422b2") }
แสดงข้อมูล
> db.demo88.find();
ผลลัพธ์:
{ "_id" : ObjectId("5e2c14c471bf0181ecc422b1"), "Name" : "Chris", "PassoutYear" : "2020", "websiteName" : "chris.shop.com/Carol-2020-" }
{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }
Query ใช้ Field Value เป็น Pattern
> db.demo88.aggregate([
{ "$match": {
"$expr": {
"$ne": [
{ "$indexOfCP": ["$websiteName", "$Name"] },
-1
]
}
}}
])
คำอธิบาย:
$indexOfCP: ["$websiteName", "$Name"]: หาตำแหน่งของค่า field Name ใน field websiteName (ใช้ code points รองรับ Unicode)$ne: [..., -1]: ผลลัพธ์ไม่เท่ากับ -1 = พบ substring$expr: อนุญาตให้ใช้ aggregation expression ใน $match
ผลลัพธ์
{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }
เอกสาร David: "David" อยู่ใน "david.bigshop.com/David-2010-" → match
เอกสาร Chris: "Chris" ไม่อยู่ใน "chris.shop.com/Carol-2020-" (มี Carol แทน) → ไม่ match
เปรียบเทียบ $indexOfCP vs $indexOfBytes
| Operator | คำอธิบาย |
|---|---|
$indexOfCP | นับด้วย Unicode code points (รองรับภาษาไทย, อิมจิ, ตัวอักษรพิเศษ) |
$indexOfBytes | นับด้วย bytes (เร็วกว่า แต่ผิดกับ multi-byte characters) |