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

Tìm tài liệu MongoDB chứa chuỗi cụ thể (Regex)

Để tìm các tài liệu chứa một chuỗi con (substring) trong trường văn bản, MongoDB sử dụng **Regular Expression (Regex)** trong phương thức find(). Cú pháp: { field: /pattern/ } hoặc { field: { $regex: "pattern", $options: "i" } }.

1. Tạo bộ sưu tập và chèn dữ liệu

> db.demo409.insertOne({ "Name": "John Doe" });
> db.demo409.insertOne({ "Name": "Chris Brown" });
> db.demo409.insertOne({ "Name": "Robert Doe" });
> db.demo409.insertOne({ "Name": "David Brown" });

2. Xem dữ liệu

> db.demo409.find();

Kết quả: 4 tài liệu với các tên khác nhau.

3. Tìm tên chứa "Doe" (không phân biệt chữ hoa/thường)

> db.demo409.find({ Name: /Doe/ });

Hoặc cú pháp đầy đủ:

> db.demo409.find({ Name: { $regex: "Doe", $options: "i" } });

4. Kết quả

{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "Robert Doe" }

Tối ưu hóa hiệu suất:

  • Regex **prefix** (/^John/) có thể dùng index thường (B-tree).
  • Regex **contains** (/Doe/) **KHÔNG** dùng được index thường -> COLLSCAN (quét toàn bộ).
  • Với tìm kiếm chứa chuỗi thường xuyên -> Tạo **Text Index**: db.demo409.createIndex({ Name: "text" }) rồi dùng $text: { $search: "Doe" }.

Options hay dùng: i (case-insensitive), m (multiline), s (dot matches newline).