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

Thiết lập regex trong MongoDB $in

MongoDB cho phép sử dụng **Regular Expression trực tiếp trong mảng $in** để khớp nhiều pattern cùng lúc. Tạo collection:

> db.demo675.insertOne({"ListOfNames":["John","Chris","David"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5b404263e90dac943ef") }
> db.demo675.insertOne({"ListOfNames":["Bob","Johnson","Sam"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5c804263e90dac943f0") }
> db.demo675.insertOne({"ListOfNames":["Jace","Sam"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5d304263e90dac943f1") }

Hiển thị dữ liệu:

> db.demo675.find();

Kết quả:

Tìm tài liệu có ListOfNames chứa giá trị khớp regex /John/ HOẶC /J/:

> db.demo675.find({"ListOfNames": {$in:[/John/,/J/]}});

Kết quả - TẤT CẢ 3 tài liệu đều khớp (John, Johnson, Jace đều khớp /J/):

Giải thích: $in với array chứa regex object [/pattern1/, /pattern2/]. Mỗi phần tử mảng ListOfNames được test với TẤT CẢ regex trong $in. Nếu KHỚP BẤT KỲ regex nào → tài liệu được chọn.

⚠️ Hiệu suất: Regex trong $in **KHÔNG sử dụng index** hiệu quả. Trên collection lớn, cân nhắc:

  • Text index + $text search
  • Atlas Search (managed)
  • Application-side filtering
  • Anchored regex /^J/ có thể dùng index prefix