ในการกรองระเบียนโดยใช้ Regular Expression ใน MongoDB ให้ใช้ $regex ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.demo19.insertOne({"Values":"4321GH"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e1389b955d0fc6657d21f0f")
}
> db.demo19.insertOne({"Values":"12321_Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e1389c755d0fc6657d21f10")
}
> db.demo19.insertOne({"Values":"8765Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e1389d355d0fc6657d21f11")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.demo19.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" }
{ "_id" : ObjectId("5e1389c755d0fc6657d21f10"), "Values" : "12321_Carol" }
{ "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" } นี่คือแบบสอบถามเพื่อใช้ regex กับการค้นหาข้อความใน MongoDB -
> db.demo19.find({Values: {$regex: /4321|8765/, $options: 'i'}}); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" }
{ "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" }