หากต้องการจำกัดจำนวนอักขระที่ส่งคืนจากฟิลด์ ให้ใช้ $substr ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> 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")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> 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."
} ต่อไปนี้เป็นแบบสอบถามเพื่อจำกัดจำนวนอักขระที่ส่งคืนจากฟิลด์ใน MongoDB -
> db.demo233.aggregate(
... [
... {
... $project:
... {
... Paragraph: { $substr: [ "$Paragraph", 0, 10] }
...
... }
...} ] ) สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e41877df4cebbeaebec5146"), "Paragraph" : "My Name is" }
{ "_id" : ObjectId("5e4187d7f4cebbeaebec5147"), "Paragraph" : "David Mill" }