Sử dụng $substr trong Aggregation Framework. Tạo collection với document:
> 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") }
Hiển thị tất cả document:
> db.limitTheNumberOfCharactersDemo.find().pretty();
Kết quả:
{ "_id" : ObjectId("5cf23013b64a577be5a2bc0e"), "Title" : "MongoDB is No SQL database" }
{ "_id" : ObjectId("5cf2302db64a577be5a2bc0f"), "Title" : "MySQL is a relational database" }
Truy vấn Aggregation cắt chuỗi Title lấy 20 ký tự đầu (từ vị trí 0):
> db.limitTheNumberOfCharactersDemo.aggregate(
[
{
$project: {
Characters: { $substr: [ "$Title", 0, 20 ] }
}
}
]
);
Kết quả:
{ "_id" : ObjectId("5cf23013b64a577be5a2bc0e"), "Characters" : "MongoDB is No SQL da" }
{ "_id" : ObjectId("5cf2302db64a577be5a2bc0f"), "Characters" : "MySQL is a relationa" }