Toán tử $substr (legacy) hoặc $substrCP / $substrBytes (MongoDB 3.4+) trong aggregate cho phép cắt chuỗi con theo vị trí và độ dài.
Dữ liệu mẫu
> db.demo233.insertOne({"Paragraph":"My Name is John Smith.I am learning MongoDB database"});
> db.demo233.insertOne({"Paragraph":"David Miller is a good student and learning Spring and Hibernate Framework."});
Pipeline aggregate $substr
> db.demo233.aggregate([
{ $project: {
Paragraph: { $substr: [ "$Paragraph", 0, 10 ] }
}}
]);
Kết quả (10 ký tự đầu)
{ "_id" : ObjectId("5e41877df4cebbeaebec5146"), "Paragraph" : "My Name is" }
{ "_id" : ObjectId("5e4187d7f4cebbeaebec5147"), "Paragraph" : "David Mill" }
3 phiên bản $substr:
| Toán tử | Đếm bằng | Phiên bản |
|---|---|---|
$substr | Bytes (legacy) | Tất cả |
$substrBytes | Bytes (UTF-8) | 3.4+ |
$substrCP | Code Points (Unicode) | 3.4+ |