Sử dụng toán tử $regex trong find() để tìm tài liệu có trường chứa chuỗi khớp mẫu. Tạo collection tên người:
> db.demo597.insertOne({"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e947ae3f5f1e70e134e2690") }
> db.demo597.insertOne({"Name":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e947ae8f5f1e70e134e2691") }
> db.demo597.insertOne({"Name":"Chris Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e947aeff5f1e70e134e2692") }
> db.demo597.insertOne({"Name":"Adam Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e947afff5f1e70e134e2693") }
Hiển thị tất cả:
> db.demo597.find();
Tìm tên chứa "smith" (không phân biệt hoa/thường):
> db.demo597.find({Name:{$regex:/smith/i}});Kết quả (John Smith, Adam Smith):
Regex patterns hữu ích:
/^pattern/- bắt đầu bằng/pattern$/- kết thúc bằng/pattern/i- case insensitive/pat.*tern/- chứa chuỗi con
^pattern). Cân nhắc text index cho tìm kiếm full-text.