สำหรับกรณี การค้นหาที่ไม่ละเอียดอ่อน ให้ใช้ regex ในวิธี find() ต่อไปนี้เป็นไวยากรณ์ -
db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}}); เพื่อให้เข้าใจไวยากรณ์ข้างต้น ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> 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")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> 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" } ต่อไปนี้เป็นคำค้นหาสำหรับการค้นหาที่ไม่คำนึงถึงตัวพิมพ์ -
> db.demo572.find({"CountryName" : { '$regex':/^US$/i}}); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }