การค้นหาชื่อที่คล้ายหรือตรงประมาณ (fuzzy/partial match) ใช้ $regex พร้อม $options: 'i' สำหรับ case-insensitive
> db.demo514.insertOne({"Information": {"FullName": "John Doe"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e885116987b6e0e9d18f58c") }
> db.demo514.insertOne({"Information": {"FullName": "John Smith"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88515e987b6e0e9d18f58d") }
> db.demo514.insertOne({"Information": {"FullName": "john doe"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e885169987b6e0e9d18f58e") }
> db.demo514.insertOne({"Information": {"FullName": "Chris Brown"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88516f987b6e0e9d18f58f") }
แสดงข้อมูล:
> db.demo514.find();
{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e88515e987b6e0e9d18f58d"), "Information" : { "FullName" : "John Smith" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }
{ "_id" : ObjectId("5e88516f987b6e0e9d18f58f"), "Information" : { "FullName" : "Chris Brown" } }
คิวรีค้นหา "John Doe" แบบไม่สนใจตัวพิมพ์เล็ก/ใหญ่
> db.demo514.find({'Information.FullName': {$regex: "John Doe", $options: 'i'}});
ผลลัพธ์ - เจอทั้ง "John Doe" และ "john doe":
รูปแบบ $regex ที่ใช้บ่อย
| Pattern | ความหมาย |
|---|---|
/John/ | มีคำว่า John อยู่ที่ไหนก็ได้ |
/^John/ | ขึ้นต้นด้วย John |
/Doe$/ | ลงท้ายด้วย Doe |
/Jo.n/ | Jon, John, Joon, etc. (จุด = ตัวอักษรอะไรก็ได้ 1 ตัว) |