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

การค้นหาข้อมูลแบบ LIKE ใน MongoDB ด้วย Regular Expression

MongoDB ไม่มีคำสั่ง LIKE โดยตรง แต่ใช้ Regular Expression (Regex) แทนได้

ตัวอย่างการใช้งาน

สร้างคอลเลกชันพร้อมข้อมูลชื่อ:

แสดงเอกสารทั้งหมด:

{ "_id" : ObjectId("5cb84984623186894665ae41"), "Name" : "John", "Age" : 32 }
{ "_id" : ObjectId("5cb84991623186894665ae42"), "Name" : "Chris", "Age" : 25 }
{ "_id" : ObjectId("5cb849a1623186894665ae43"), "Name" : "Carol", "Age" : 22 }
{ "_id" : ObjectId("5cb849b2623186894665ae44"), "Name" : "Johnny", "Age" : 22 }
{ "_id" : ObjectId("5cb849bb623186894665ae45"), "Name" : "James", "Age" : 27 }

ค้นหาชื่อขึ้นต้นด้วย "Jo" (Case Insensitive)

{ "_id" : ObjectId("5cb84984623186894665ae41"), "Name" : "John", "Age" : 32 }
{ "_id" : ObjectId("5cb849b2623186894665ae44"), "Name" : "Johnny", "Age" : 22 }

Regex Patterns ที่นิยม:

  • /^pattern/ - เริ่มต้นด้วย (LIKE 'pattern%')
  • /pattern$/ - จบด้วย (LIKE '%pattern')
  • /pattern/ - มีอยู่ที่ไหนก็ได้ (LIKE '%pattern%')
  • /pattern/i - Case Insensitive