Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ค้นหาเอกสารที่มีค่าเฉพาะด้วย Regular Expressions ใน MongoDB


ใช้ $regex สำหรับ Pattern Matching

Operator $regex ช่วยค้นหาข้อความที่ตรงกับรูปแบบ (pattern) รองรับ Regular Expressions ทั้งหมด พร้อม options เช่น case-insensitive

ตัวอย่างข้อมูล

> db.demo469.insertOne({ "StudentName": "John Doe" });
> db.demo469.insertOne({ "StudentName": "Chris Brown" });
> db.demo469.insertOne({ "StudentName": "John Smith" });
> db.demo469.insertOne({ "StudentName": "Jace Doe" });
> db.demo469.insertOne({ "StudentName": "David Miller" });

Query ค้นหาชื่อที่มี "john" (ไม่สนใจพิมพ์เล็ก/ใหญ่)

> db.demo469.find({ 'StudentName': { '$regex': 'john', '$options': 'i' } });

ผลลัพธ์

{ "_id": ObjectId(...), "StudentName": "John Doe" }
{ "_id": ObjectId(...), "StudentName": "John Smith" }

Regex Options

รูปแบบการใช้งาน

// Object syntax (แนะนำ)
{ field: { $regex: "pattern", $options: "i" } }

// Shorthand syntax
{ field: /pattern/i }

// ใช้กับ $in
{ field: { $in: [/john/i, /jane/i] } }

ประสิทธิภาพ (Performance)

  • Anchored regex (ขึ้นต้นด้วย ^) ใช้ index ได้: /^john/i
  • Unanchored regex ไม่ใช้ index: /john/i - ต้อง scan ทุกเอกสาร
  • สร้าง text index สำหรับ full-text search ที่ซับซ้อน

ตัวอย่าง Pattern พิเศษ

// เริ่มต้นด้วย John
{ StudentName: { $regex: "^John", $options: "i" } }

// จบด้วย Doe
{ StudentName: { $regex: "Doe$", $options: "i" } }

// มีตัวเลข
{ StudentName: { $regex: "\\d" } }

// Email pattern
{ email: { $regex: "^[\\w.-]+@[\\w.-]+\\.\\w+$" } }
Optionคำอธิบาย
iCase-insensitive (ไม่สนใจพิมพ์เล็ก/ใหญ่)
mMultiline (^ และ $ match เริ่ม/จบบรรทัด)
xExtended (ignore whitespace, อนุญาต comment)
sDot matches newline (. match \n ได้)