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

วิธี Query MongoDB ตามความยาวสตริง (String Length) ด้วย Regex

ใช้ 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

วิธีอื่น: ใช้ $strLenCP (Aggregation, MongoDB 3.4+)

db.collection.aggregate([
    { $project: { 
        name: 1, 
        nameLength: { $strLenCP: "$StudentFullName" } 
    }},
    { $match: { nameLength: { $gte: 9, $lte: 12 } }}
]);

วิธีนี้แม่นยำกว่า (นับ Unicode code points) และเร็วกว่าสำหรับข้อมูลมาก

สรุป

  • ใช้ $regex: /^.{min,max}$/ สำหรับ query ความยาวสตริงง่ายๆ
  • ใช้ $strLenCP ใน Aggregation สำหรับความแม่นยำและประสิทธิภาพดีกว่า
  • Regex ใช้ index ได้เฉพาะ prefix pattern (^abc) ไม่ได้กับ length pattern
  • ควรสร้าง index บนฟิลด์ที่ query บ่อย
ส่วนความหมาย
^เริ่มต้นสตริง
.ตัวอักษรใดๆ (ยกเว้น newline)
{9,12}จำนวน 9 ถึง 12 ครั้ง
$สิ้นสุดสตริง
/ ... /Regex delimiter