Computer >> Máy Tính >  >> Lập trình >> MongoDB

Truy vấn MongoDB với tìm kiếm không phân biệt chữ hoa chữ thường?

Đối với tìm kiếm không phân biệt chữ hoa chữ thường, hãy sử dụng phương thức regex trong find (). Sau đây là cú pháp -

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

Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với các tài liệu -

> 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ả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.demo572.find();

Điều này sẽ tạo ra kết quả sau -

{ "_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" }

Sau đây là truy vấn cho tìm kiếm không phân biệt chữ hoa chữ thường -

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

Điều này sẽ tạo ra kết quả sau -

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