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

Tìm kiếm không phân biệt chữ hoa thường (case insensitive) trong MongoDB

Để tìm kiếm không phân biệt chữ hoa/thường, sử dụng Regular Expression (regex) với cờ i trong phương thức find().

Cú pháp:

db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});

Tạo collection với tên quốc gia (có biến thể chữ hoa/thường):

> db.demo572.insertOne({"CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1") }
> db.demo572.insertOne({"CountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2") }
> db.demo572.insertOne({"CountryName":"Us"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3") }
> db.demo572.insertOne({"CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4") }
> db.demo572.insertOne({"CountryName":"us"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5") }

Hiển thị tất cả:

> db.demo572.find();
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }

Tìm kiếm case-insensitive cho "US":

> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});

Kết quả (khớp US, Us, us):

{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }

Giải thích regex:

  • ^ - bắt đầu chuỗi
  • $ - kết thúc chuỗi
  • /i - case insensitive
  • /^US$/i khớp chính xác "US" bất kể chữ hoa/thường