ใช้ Regular Expression (Regex) เพื่อค้นหาข้อมูลแบบรูปแบบ (pattern matching) เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "John" },"StudentAge":21 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227acb64a577be5a2bc07") }
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "JOHN" },"StudentAge":19 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227b8b64a577be5a2bc08") }
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "Carol" },"StudentAge":20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227c2b64a577be5a2bc09") }
แสดงเอกสารทั้งหมด:
> db.workingOfRegularExpressionDemo.find();
คิวรี่ใช้ Regex ค้นหา StudentName เป็น "JOHN" (case-sensitive):
> db.workingOfRegularExpressionDemo.find({'StudentDetails.StudentName': /JOHN/});ใช้ตัวเลือก
$options: 'i'เพื่อค้นหาแบบไม่สนใจตัวพิมพ์เล็ก/ใหญ่ (case-insensitive):> db.workingOfRegularExpressionDemo.find({'StudentDetails.StudentName': { $regex: 'JOHN', $options: 'i' }});รูปแบบ Regex ใน MongoDB: ใช้เครื่องหมาย
/pattern/หรือออบเจกต์{$regex: 'pattern', $options: 'options'}ตัวเลือกทั่วไป:i(case-insensitive),m(multiline),s(dot matches newline)