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

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

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

ตัวอย่างข้อมูลทดสอบ (ข้อความยาว)

> db.demo233.insertOne({"Paragraph": "My Name is John Smith.I am learning MongoDB database"});
{ "acknowledged": true, "insertedId": ObjectId("5e41877df4cebbeaebec5146") }
> db.demo233.insertOne({"Paragraph": "David Miller is a good student and learning Spring and Hibernate Framework."});
{ "acknowledged": true, "insertedId": ObjectId("5e4187d7f4cebbeaebec5147") }

แสดงข้อมูลต้นฉบับ

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

ผลลัพธ์

{
  "_id": ObjectId("5e41877df4cebbeaebec5146"),
  "Paragraph": "My Name is John Smith.I am learning MongoDB database"
}
{
  "_id": ObjectId("5e4187d7f4cebbeaebec5147"),
  "Paragraph": "David Miller is a good student and learning Spring and Hibernate Framework."
}

ใช้ $substr ตัดข้อความ 10 ตัวอักษรแรก

> db.demo233.aggregate([
    {
      $project: {
        Paragraph: { $substr: ["$Paragraph", 0, 10] }
      }
    }
  ]);

ผลลัพธ์ (เหลือ 10 ตัวอักษรแรก)

{
  "_id": ObjectId("5e41877df4cebbeaebec5146"),
  "Paragraph": "My Name is"
}
{
  "_id": ObjectId("5e4187d7f4cebbeaebec5147"),
  "Paragraph": "David Mill"
}

พารามิเตอร์ $substr: [$field, startIndex, length]

  • startIndex: ตำแหน่งเริ่มต้น (0 = ตัวแรก)
  • length: จำนวนตัวอักษรที่ต้องการ

หมายเหตุ: ใน MongoDB 3.4+ ควรใช้ $substrBytes (นับเป็นไบต์) หรือ $substrCP (นับเป็น Unicode code points) แทน $substr ที่ล้าสมัย