Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tìm document chứa giá trị cụ thể với Regular Expression MongoDB

Tìm kiếm văn bản với Regular Expression ($regex)

Sử dụng $regex để tìm document chứa chuỗi con, không phân biệt chữ hoa/thường, khớp mẫu phức tạp.

1. Dữ liệu mẫu

> 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" });

2. Tìm tên chứa "john" (case-insensitive)

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

3. Kết quả

{ "_id": ObjectId("5e80532fb0f3fa88e227906b"), "StudentName": "John Doe" }
{ "_id": ObjectId("5e805341b0f3fa88e227906d"), "StudentName": "John Smith" }

Các options quan trọng

OptionÝ nghĩa
iCase-insensitive (không phân biệt hoa/thường)
mMultiline - ^ và $ khớp đầu/cuối dòng
sDot matches newline (.) khớp xuống dòng)
xExtended - bỏ qua whitespace, cho phép comment

Cú pháp thay thế (short form)

// Tương đương nhau:
db.demo469.find({ StudentName: /john/i });
db.demo469.find({ StudentName: { $regex: /john/i } });
db.demo469.find({ StudentName: { $regex: "john", $options: "i" } });

Các pattern hay dùng

// Bắt đầu bằng "John"
{ $regex: "^John", $options: "i" }

// Kết thúc bằng "Doe"
{ $regex: "Doe$", $options: "i" }

// Chứa "ohn" ở giữa
{ $regex: "ohn", $options: "i" }

// Từ hoàn chỉnh "John" (word boundary)
{ $regex: "\\bJohn\\b", $options: "i" }

// Phân cách bởi khoảng trắng
{ $regex: "\\sJohn\\s", $options: "i" }

⚠️ Hiệu suất & Index

  • Chỉ dùng index khi pattern là prefix (^...) và không có option 'i'
  • /^john/i → KHÔNG dùng index (do option 'i')
  • /^John/ → CÓ dùng index (prefix, case-sensitive)
  • Với tìm kiếm full-text → dùng Text Index (db.coll.createIndex({ field: "text" }))

So sánh $regex vs Text Search

Đặc điểm$regexText Index ($text)
Hỗ trợ từ ngữKhó✅ Tự động tách từ, stem
Hiệu suất text lớnChậm (full scan)✅ Nhanh (inverted index)
Regex phức tạp✅ Hỗ trợ đầy đủ❌ Không hỗ trợ
Case-insensitiveOption 'i'✅ Mặc định