ใช้ Regular Expression ($regex) เพื่อค้นหาเอกสารที่ความยาวของสตริงอยู่ในช่วงที่กำหนด
รูปแบบ Regex สำหรับความยาว
// ความยาวระหว่าง min ถึง max
/^.{min,max}$/
// ความยาวแน่นอน
/^.{exactLength}$/
// ความยาวมากกว่าหรือเท่ากับ min
/^.{min,}$/
ตัวอย่างเต็มรูปแบบ
1. สร้างข้อมูลตัวอย่าง (ชื่อ-นามสกุล ความยาวต่างกัน)
> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"}); // 10 chars
> db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"}); // 8 chars
> db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"}); // 12 chars
> db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"}); // 13 chars
> db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"}); // 14 chars
2. แสดงข้อมูลทั้งหมด
> db.queryLengthDemo.find().pretty();
3. ค้นหาความยาว 9-12 ตัวอักษร
> db.queryLengthDemo.find({
StudentFullName: { $regex: /^.{9,12}$/ }
}).pretty();
4. ผลลัพธ์: John Smith (10), David Miller (12)
{ "_id" : ..., "StudentFullName" : "John Smith" }
{ "_id" : ..., "StudentFullName" : "David Miller" }
คำอธิบาย Regex Pattern
| ส่วน | ความหมาย |
|---|---|
^ | เริ่มต้นสตริง |
. | ตัวอักษรใดๆ (ยกเว้น newline) |
{9,12} | จำนวน 9 ถึง 12 ครั้ง |
$ | สิ้นสุดสตริง |
/ ... / | Regex delimiter |