Để tìm tên tương tự (fuzzy search) với Regular Expression, sử dụng $regex kết hợp tùy chọn $options: 'i' (case-insensitive). Tạo collection:
> db.demo514.insertOne({"Information":{"FullName":"John Doe"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e885116987b6e0e9d18f58c") }
> db.demo514.insertOne({"Information":{"FullName":"John Smith"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88515e987b6e0e9d18f58d") }
> db.demo514.insertOne({"Information":{"FullName":"john doe"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e885169987b6e0e9d18f58e") }
> db.demo514.insertOne({"Information":{"FullName":"Chris Brown"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88516f987b6e0e9d18f58f") }
Hiển thị dữ liệu:
> db.demo514.find();
Kết quả (có cả "John Doe" và "john doe"):
Tìm tên chứa "John Doe" không phân biệt hoa/thường:
> db.demo514.find({'Information.FullName': {$regex: "John Doe", $options: 'i'}});Kết quả khớp cả "John Doe" và "john doe":
Mở rộng: Để tìm tên BẮT ĐẦU bằng "John":
{$regex: /^John/, $options: 'i'}. Để tìm tên KẾT THÚC bằng "Doe":{$regex: /Doe$/, $options: 'i'}. Dấu^= đầu chuỗi,$= cuối chuỗi.