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

จำกัดจำนวนตัวอักษรที่คืนค่าจากฟิลด์ในคิวรี่ MongoDB

ใช้ตัวดำเนินการ $substr (หรือ $substrBytes/$substrCP ในรุ่นใหม่) ใน Aggregate Framework เพื่อตัดข้อความให้เหลือจำนวนตัวอักษรที่ต้องการ เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.limitTheNumberOfCharactersDemo.insertOne({"Title":"MongoDB is No SQL database"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf23013b64a577be5a2bc0e") }
> db.limitTheNumberOfCharactersDemo.insertOne({"Title":"MySQL is a relational database"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf2302db64a577be5a2bc0f") }

แสดงเอกสาร:

> db.limitTheNumberOfCharactersDemo.find().pretty();

คิวรี่ Aggregate ตัดข้อความ Title ให้เหลือ 20 ตัวอักษรแรก:

> db.limitTheNumberOfCharactersDemo.aggregate([
  { $project: { Characters: { $substr: [ "$Title", 0, 20 ] } } }
]);

ตัวดำเนินการ substring ใน MongoDB:

  • $substr - ตัดตาม bytes (legacy)
  • $substrBytes - ตัดตาม bytes (UTF-8)
  • $substrCP - ตัดตาม code points (ตัวอักษรจริง) แนะนำสำหรับภาษาไทย
รูปแบบ: { $substrCP: [ "$field", startIndex, length ] }