ใน MongoDB สามารถใช้โอเปอเรเตอร์ $regex เพื่อกรองข้อมูลด้วย Regular Expression ได้ ให้สร้างคอลเลกชันตัวอย่างก่อน:
> db.demo19.insertOne({"Values":"4321GH"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e1389b955d0fc6657d21f0f") }
> db.demo19.insertOne({"Values":"12321_Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e1389c755d0fc6657d21f10") }
> db.demo19.insertOne({"Values":"8765Mike"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e1389d355d0fc6657d21f11") }
แสดงข้อมูลทั้งหมด:
> db.demo19.find();
ผลลัพธ์:
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" }
{ "_id" : ObjectId("5e1389c755d0fc6657d21f10"), "Values" : "12321_Carol" }
{ "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" }
คิวรีใช้ $regex ค้นหาข้อมูลที่ขึ้นต้นด้วย 4321 หรือ 8765 (ไม่สนใจตัวพิมพ์เล็ก/ใหญ่):
> db.demo19.find({Values: {$regex: /4321|8765/, $options: 'i'}});
ผลลัพธ์ที่ได้:
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" }
{ "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" }
รายละเอียดเพิ่มเติม
$options: 'i'ทำให้การค้นหาไม่สนใจตัวพิมพ์เล็ก/ใหญ่ (case-insensitive)- รูปแบบ
/pattern/เป็นรูปแบบ regex แบบ native ของ MongoDB - สัญลักษณ์
|หมายถึง "หรือ" (OR condition) - สามารถใช้ regex แบบ string ได้เช่น
{$regex: "4321|8765", $options: "i"}