Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ตั้งค่า Regex ใน MongoDB $in Operator

การใช้ Regular Expression ภายใน $in เพื่อค้นหาเอกสารที่อาร์เรย์มีค่า match regex ใดๆ

> db.demo675.insertOne({"ListOfNames": ["John", "Chris", "David"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5b404263e90dac943ef") }
> db.demo675.insertOne({"ListOfNames": ["Bob", "Johnson", "Sam"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5c804263e90dac943f0") }
> db.demo675.insertOne({"ListOfNames": ["Jace", "Sam"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f5d304263e90dac943f1") }

แสดงข้อมูล:

> db.demo675.find();

คิวรี $in พร้อม Regex: หาที่ขึ้นต้น J หรือมี John

> db.demo675.find({"ListOfNames": {$in: [/John/, /J/]}});

ผลลัพธ์ - ทั้ง 3 เอกสาร match (ทุกอันมีค่าเริ่ม J หรือมี John):


คำอธิบาย

  • /John/ - match คำว่า "John" อยู่ที่ไหนก็ได้ในสตริง
  • /J/ - match ตัวอักษร J อยู่ที่ไหนก็ได้ (ในที่นี้ match ทุกค่าที่มี J)
  • $in: [/regex1/, /regex2/] - match ถ้าอาร์เรย์มีสมาชิกตรง regex ใด regex หนึ่ง

ข้อควรระวัง

  • Regex ใน $in ไม่ใช้ Index ได้ (Full scan)
  • เหมาะสำหรับข้อมูลเล็ก หรือ ad-hoc query
  • Production ใหญ่ ควรใช้ Text Search หรือออกแบบ Schema ให้ query ได้โดยไม่ต้อง regex

ตัวอย่าง Pattern อื่นๆ

// เริ่มต้นด้วย J
{$in: [/^J/]}

// ลงท้ายด้วย n
{$in: [/n$/]}

// มี "oh" อยู่กลาง
{$in: [/oh/]}